import Foundation
import UIKit

/// people list view controller
class OsobyListViewController: UIViewController {
    var viewModel: OsobyListViewModelProtocol?
    
    /// initialization function
    /// - Parameter viewModel: view model of people list
    init(viewModel: OsobyListViewModelProtocol) {
        super.init(nibName: nil, bundle: nil)
        let view = OsobyListView()
        view.viewDelegate = self
        self.viewModel = viewModel
        self.viewModel?.delegate = self
        self.view = view
    }
    
    /// function that gets called before the view appears
    /// - Parameter animated: animated
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(true)
        navigationController?.setNavigationBarHidden(false, animated: false)
        title = "Osoby"
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension OsobyListViewController: OsobyListViewModelDelegate {
    
    /// function that gets called after the view model was updated
    func didUpdate() {
        DispatchQueue.main.async {
            guard let view = self.view as? OsobyListView else { return }
            view.viewModel = self.viewModel
        }
    }
}

extension OsobyListViewController: OsobyListViewDelegate {
    
    /// function that gets called when the user selected a person to present its detail
    /// - Parameter id: id of the person
    func selectedPerson(id: String) {
        let controller = OsobaViewController()
        controller.viewModel = OsobaViewModel(id: id)
        navigationController?.pushViewController(controller, animated: true)
    }
}
