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

import UIKit
import Pachyderm

@MainActor
class DeleteListService {
    private let list: List
    private let mastodonController: MastodonController
    private let present: (UIViewController) -> Void
    
    init(list: List, mastodonController: MastodonController, present: @escaping (UIViewController) -> Void) {
        self.list = list
        self.mastodonController = mastodonController
        self.present = present
    }

    @discardableResult
    func run() async -> Bool {
        if await presentConfirmationAlert() {
            await deleteList()
            return true
        } else {
            return false
        }
    }
    
    private func presentConfirmationAlert() async -> Bool {
        await withCheckedContinuation { continuation in
            let titleFormat = NSLocalizedString("Are you sure you want to delete the '%@' list?", comment: "delete list alert title")
            let title = String(format: titleFormat, list.title)
            let alert = UIAlertController(title: title, message: nil, preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: NSLocalizedString("Cancel", comment: "delete list alert cancel button"), style: .cancel, handler: { (_) in
                continuation.resume(returning: false)
            }))
            alert.addAction(UIAlertAction(title: NSLocalizedString("Delete List", comment: "delete list alert confirm button"), style: .destructive, handler: { (_) in
                continuation.resume(returning: true)
            }))
            present(alert)
        }
    }
    
    private func deleteList() async {
        do {
            let request = List.delete(list.id)
            _ = try await mastodonController.run(request)
            mastodonController.deletedList(list)
        } catch {
            let alert = UIAlertController(title: "Error Deleting List", message: error.localizedDescription, preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "Cancel", style: .cancel))
            alert.addAction(UIAlertAction(title: "Retry", style: .default, handler: { _ in
                Task {
                    await self.deleteList()
                }
            }))
            present(alert)
        }
    }
}
