//
//  FavoriteService.swift
//  Tusker
//
//  Created by Shadowfacts on 10/8/22.
//  Copyright © 2022 Shadowfacts. All rights reserved.
//

import UIKit
import Pachyderm

@MainActor
class FavoriteService {
    
    private let mastodonController: MastodonController
    private let presenter: any TuskerNavigationDelegate
    private let status: StatusMO
    
    var hapticFeedback = true
    
    init(status: StatusMO, mastodonController: MastodonController, presenter: any TuskerNavigationDelegate) {
        self.status = status
        self.mastodonController = mastodonController
        self.presenter = presenter
    }
    
    func toggleFavorite() async {
        let oldValue = status.favourited
        status.favourited.toggle()
        mastodonController.persistentContainer.statusSubject.send(status.id)
        
        if hapticFeedback {
            UIImpactFeedbackGenerator(style: .light).impactOccurred()
        }
        
        let request = (status.favourited ? Status.favourite : Status.unfavourite)(status.id)
        do {
            let (newStatus, _) = try await mastodonController.run(request)
            mastodonController.persistentContainer.addOrUpdate(status: newStatus)
        } catch {
            status.favourited = oldValue
            mastodonController.persistentContainer.statusSubject.send(status.id)
            
            let title = oldValue ? "Error Unfavoriting" : "Error Favoriting"
            let config = ToastConfiguration(from: error, with: title, in: presenter) { toast in
                // deliberately retain a strong reference to self
                toast.dismissToast(animated: true)
                await self.toggleFavorite()
            }
            presenter.showToast(configuration: config, animated: true)
            
            if hapticFeedback {
                UINotificationFeedbackGenerator().notificationOccurred(.error)
            }
        }
    }
    
}
