//
//  ToggleFollowHashtagService.swift
//  Tusker
//
//  Created by Shadowfacts on 11/29/22.
//  Copyright © 2022 Shadowfacts. All rights reserved.
//

import UIKit
import Pachyderm

@MainActor
class ToggleFollowHashtagService {
    
    private let hashtagName: String
    private let mastodonController: MastodonController
    private let presenter: any TuskerNavigationDelegate
    
    init(hashtagName: String, presenter: any TuskerNavigationDelegate) {
        self.hashtagName = hashtagName
        self.mastodonController = presenter.apiController
        self.presenter = presenter
    }
    
    @discardableResult
    func toggleFollow() async -> Bool {
        let success: Bool
        let context = mastodonController.persistentContainer.viewContext
        var config: ToastConfiguration
        if let existing = mastodonController.followedHashtags.first(where: { $0.name == hashtagName }) {
            do {
                let req = Hashtag.unfollow(name: hashtagName)
                _ = try await mastodonController.run(req)
                
                context.delete(existing)
                mastodonController.updateFollowedHashtags()
                
                config = ToastConfiguration(title: "Unfollowed Hashtag")
                config.systemImageName = "checkmark"
                config.dismissAutomaticallyAfter = 2
                
                success = true
            } catch {
                config = ToastConfiguration(from: error, with: "Error Unfollowing Hashtag", in: presenter) { toast in
                    toast.dismissToast(animated: true)
                    await self.toggleFollow()
                }
                success = false
            }
        } else {
            do {
                let req = Hashtag.follow(name: hashtagName)
                let (hashtag, _) = try await mastodonController.run(req)
                
                _ = FollowedHashtag(hashtag: hashtag, context: context)
                mastodonController.updateFollowedHashtags()
                
                config = ToastConfiguration(title: "Followed Hashtag")
                config.systemImageName = "checkmark"
                config.dismissAutomaticallyAfter = 2
                
                success = true
            } catch {
                config = ToastConfiguration(from: error, with: "Error Following Hashtag", in: presenter) { toast in
                    toast.dismissToast(animated: true)
                    await self.toggleFollow()
                }
                success = false
            }
        }
        presenter.showToast(configuration: config, animated: true)
        mastodonController.persistentContainer.save(context: context)
        return success
    }
    
}
