
import UIKit

protocol LocationAlertVCDelegate {
    func handleCountrySelection(country: CountryModel)
}

class LocationAlertVC: UIViewController {
    
    // MARK: - IBOutlets
    
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var tableViewHeight: NSLayoutConstraint!
    @IBOutlet weak var closeButton: UIButton!
    
    // MARK: - Properties
    
    let countries = CountryData.instance.countries
    var delegate: LocationAlertVCDelegate?
    
    // MARK: - View Life Cycles
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        
        self.initialConfig()
    }
    
    // MARK: - Selectors
    
    // Close Button Action
    @IBAction func closeButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        self.dismiss(animated: true, completion: nil)
    }
    
    // MARK: - Helper Functions
    
    // Initial Config
    func initialConfig() {
        self.view.backgroundColor = .black.withAlphaComponent(0.4)
        self.tableViewSetUp()
    }
    
    // TableView SetUp
    func tableViewSetUp() {
        self.tableView.delegate = self
        self.tableView.dataSource = self
        self.tableView.register(UINib(resource: R.nib.locationCell), forCellReuseIdentifier: R.reuseIdentifier.locationCell.identifier)
        self.tableView.reloadData()
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.01) {
            if self.tableView.contentSize.height > (self.view.frame.height * 0.7) {
                self.tableViewHeight.constant = (self.view.frame.height * 0.7)
            } else {
                self.tableViewHeight.constant = self.tableView.contentSize.height
            }
        }
    }
    
}

// MARK: - Extensions

// MARK: TableView Setup
extension LocationAlertVC: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.countries.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = self.tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.locationCell.identifier, for: indexPath) as! LocationCell
        cell.titleLabel.text = self.countries[indexPath.row].name
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let country = self.countries[indexPath.row]
        self.dismiss(animated: true) {
            self.delegate?.handleCountrySelection(country: country)
        }
    }
    
}
