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

import UIKit
import Pachyderm

@MainActor
class RenameListService {
    private let list: ListProtocol
    private let mastodonController: MastodonController
    private let present: (UIViewController) -> Void

    private var renameAction: UIAlertAction?
    
    init(list: ListProtocol, mastodonController: MastodonController, present: @escaping (UIViewController) -> Void) {
        self.list = list
        self.mastodonController = mastodonController
        self.present = present
    }
    
    func run() {
        let alert = UIAlertController(title: NSLocalizedString("Rename List", comment: "rename list alert title"), message: nil, preferredStyle: .alert)
        alert.addTextField { (textField) in
            textField.text = self.list.title
            textField.addTarget(self, action: #selector(self.alertTextFieldValueChanged), for: .editingChanged)
        }
        alert.addAction(UIAlertAction(title: NSLocalizedString("Cancel", comment: "rename list alert cancel button"), style: .cancel, handler: nil))
        renameAction = UIAlertAction(title: NSLocalizedString("Rename", comment: "renaem list alert rename button"), style: .default, handler: { (_) in
            let textField = alert.textFields!.first!
            let title = textField.text ?? ""
            Task {
                await self.updateList(with: title)
            }
        })
        alert.addAction(renameAction!)
        present(alert)
    }
    
    @objc private func alertTextFieldValueChanged(_ textField: UITextField) {
        renameAction?.isEnabled = textField.text?.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty == false
    }
    
    private func updateList(with title: String) async {
        do {
            let req = List.update(list.id, title: title, replyPolicy: nil, exclusive: nil)
            let (list, _) = try await mastodonController.run(req)
            mastodonController.updatedList(list)
        } catch {
            let alert = UIAlertController(title: "Error Updating 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.updateList(with: title)
                }
            }))
            present(alert)
        }
    }

}
