import UIKit

/// unit members view model protocol
protocol ClenoveJednotkyViewModelProtocol {
    var delegate: ClenoveJednotkyViewModelDelegate? { get set }
    var loading: Bool { get }
    var items: [Membership] { get }
    func refreshData()
}

/// unit members view model protocol delegate
protocol ClenoveJednotkyViewModelDelegate: AnyObject {
    func didUpdate()
}

/// unit members view model
class ClenoveJednotkyViewModel: ClenoveJednotkyViewModelProtocol {
    weak var delegate: ClenoveJednotkyViewModelDelegate?
    var loading: Bool = true
    var items: [Membership] = []
    private var id: String
    
    /// initialization function
    /// - Parameter id: id for unit
    init(id: String) {
        self.id = id
    }
    
    /// function that refreshes and sets the data for unit members view model
    func refreshData() {
        guard let token = UserDefaults.userToken else { return }
        let unit = MembershipAll(ID_Login: token, ID_Unit: id)
        let output = MembershipAllResult(completion: { [weak self] result in
            guard let res = result as? MembershipAllResult else { return }
            self?.items = res.MembershipAllOutput
            self?.loading = false
            self?.delegate?.didUpdate()
        })
        API.shared.call(object: unit, result: output, serviceName: .organizationUnit)
    }
    
}
