//
//  EditListSettingsService.swift
//  Tusker
//
//  Created by Shadowfacts on 10/28/23.
//  Copyright © 2023 Shadowfacts. All rights reserved.
//

import UIKit
import Pachyderm

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

    init(list: ListProtocol, mastodonController: MastodonController, present: @escaping (UIViewController) -> Void) {
        self.list = list
        self.mastodonController = mastodonController
        self.present = present
    }
    
    func run(title: String? = nil, replyPolicy: List.ReplyPolicy? = nil, exclusive: Bool? = nil) async {
        do {
            let req = List.update(
                list.id,
                title: title ?? list.title,
                replyPolicy: replyPolicy ?? list.replyPolicy,
                exclusive: exclusive ?? list.exclusive
            )
            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.run(title: title, replyPolicy: replyPolicy, exclusive: exclusive)
                }
            }))
            present(alert)
        }
    }

}
