import Foundation
import UIKit

/// registration view controller
class RegistraceViewController: UIViewController {
    
    var viewModel: RegistraceViewModelProtocol?
    
    /// initialization function
    /// - Parameter viewModel: registration view model
    init(viewModel: RegistraceViewModelProtocol) {
        super.init(nibName: nil, bundle: nil)
        self.viewModel = viewModel
        self.viewModel?.delegate = self
        let view = RegistraceView()
        view.headerView.delegate = self
        self.view = view
        self.viewModel?.refreshData()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /// 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 = "Členové Jednotky"
    }
}

extension RegistraceViewController: RegistraceViewModelDelegate {
    
    /// function that updates the view model
    func didUpdate() {
        DispatchQueue.main.async {
            guard let view = self.view as? RegistraceView else { return }
            view.viewModel = self.viewModel
        }
    }
}

extension RegistraceViewController: RegistraceHeaderViewDelegate {
    
    /// functoin that displays an allert with a given year for selection
    func yearTap() {
        guard let years = viewModel?.years else { return }
        let alertController = UIAlertController(title: "Vyberte rok", message: nil, preferredStyle: .alert)
        years.forEach({ item in
            let alert = UIAlertAction(title: item.Year, style: .default, handler: { [weak self] _ in
                self?.viewModel?.getRegistations(for: item)
                self?.viewModel?.currentYear = item
            })
            alertController.addAction(alert)
        })
        present(alertController, animated: true, completion: nil)
    }
}
