import Foundation

/// protocol for poeple list view model
protocol OsobyListViewModelProtocol {
    var delegate: OsobyListViewModelDelegate? { get set }
    var loading: Bool { get }
    var items: [Person] { get }
    func reloadData(query: String, jednotky: Bool, skauti: Bool)
}

/// poeple list view model delegate
protocol OsobyListViewModelDelegate: AnyObject {
    func didUpdate()
}

/// people list view model
class OsobyListViewModel: OsobyListViewModelProtocol {
    weak var delegate: OsobyListViewModelDelegate?
    var loading: Bool = false
    var items: [Person] {
        var celkove: [Person] = []
        celkove.append(contentsOf: osoby)
        celkove.append(contentsOf: skauti)
        return celkove
    }
    private var skauti: [Person] = []
    private var osoby: [Person] = []
    
    /// fucntion that reloads data for the view model and sets its variables
    /// - Parameters:
    ///   - query: query
    ///   - jednotky: boolean for unit
    ///   - skauti: boolean for the whole system
    func reloadData(query: String, jednotky: Bool, skauti: Bool) {
        guard let token = UserDefaults.userToken else { return }
        loading = true
        if jednotky {
            loadJednotky(token: token, query: query)
        }
        if skauti {
            loadSkauti(token: token, query: query)
        }
    }
    
    /// function that loads unit people based on query
    /// - Parameters:
    ///   - token: user token
    ///   - query: query
    private func loadJednotky(token: String, query: String) {
        let person = PersonAll(ID_Login: token, DisplayName: query)
        let output = PersonAllResult(completion: { [weak self] result in
            guard let res = result as? PersonAllResult else { return }
            self?.osoby = res.PersonAllOutput
            self?.loading = false
            self?.delegate?.didUpdate()
        })
        API.shared.call(object: person, result: output, serviceName: .organizationUnit)
    }
    
    /// function that loads whole system people based on query
    /// - Parameters:
    ///   - token: user token
    ///   - query: query
    private func loadSkauti(token: String, query: String) {
        let person = PersonAllCatalog(ID_Login: token, Name: query)
        let output = PersonAllCatalogResult(completion: { [weak self] result in
            guard let res = result as? PersonAllCatalogResult else { return }
            self?.skauti = res.PersonAllCatalogOutput
            self?.loading = false
            self?.delegate?.didUpdate()
        })
        API.shared.call(object: person, result: output, serviceName: .organizationUnit)
    }
    
}
