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

import UIKit
import Pachyderm

@MainActor
class CreateListService {
    private let mastodonController: MastodonController
    private let present: (UIViewController) -> Void
    private let didCreateList: (@MainActor (List) async -> Void)?
    
    private var createAction: UIAlertAction?
    
    init(mastodonController: MastodonController, present: @escaping (UIViewController) -> Void, didCreateList: (@MainActor (List) async -> Void)?) {
        self.mastodonController = mastodonController
        self.present = present
        self.didCreateList = didCreateList
    }
    
    func run() {
        let alert = UIAlertController(title: NSLocalizedString("New List", comment: "new list alert title"), message: NSLocalizedString("Choose a title for your new list", comment: "new list alert message"), preferredStyle: .alert)
        alert.addTextField { textField in
            textField.addTarget(self, action: #selector(self.alertTextFieldValueChanged), for: .editingChanged)
        }
        alert.addAction(UIAlertAction(title: NSLocalizedString("Cancel", comment: "new list alert cancel button"), style: .cancel, handler: nil))
        createAction = UIAlertAction(title: NSLocalizedString("Create List", comment: "new list create button"), style: .default, handler: { (_) in
            let textField = alert.textFields!.first!
            let title = textField.text ?? ""
            Task {
                await self.createList(with: title)
            }
        })
        createAction!.isEnabled = false
        alert.addAction(createAction!)
        present(alert)
    }
    
    @objc private func alertTextFieldValueChanged(_ textField: UITextField) {
        createAction?.isEnabled = textField.text?.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty == false
    }
    
    private func createList(with title: String) async {
        do {
            let request = Client.createList(title: title)
            let (list, _) = try await mastodonController.run(request)
            mastodonController.addedList(list)
            await self.didCreateList?(list)
        } catch {
            let alert = UIAlertController(title: "Error Creating 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.createList(with: title)
                }
            }))
            present(alert)
        }
    }
    
}
