import Foundation
import UIKit

/// people list protocol for delegates
protocol OsobyListViewDelegate: AnyObject {
    func selectedPerson(id: String)
}

/// people list view
class OsobyListView: UITableView {
    var viewModel: OsobyListViewModelProtocol? {
        didSet {
            guard let viewModel = viewModel else { return }
                if viewModel.loading {
                    activityIndicator.startAnimating()
                } else {
                    activityIndicator.stopAnimating()
                    emptyLabel.isHidden = !viewModel.items.isEmpty
                }
                reloadData()
            }
    }
    
    weak var viewDelegate: OsobyListViewDelegate?
    
    private let activityIndicator: UIActivityIndicatorView = {
        let view = UIActivityIndicatorView()
        view.translatesAutoresizingMaskIntoConstraints = false
        view.style = .large
        view.color = scoutBlue
        view.startAnimating()
        return view
    }()
    
    private let emptyLabel: UILabel = {
        let view = UILabel()
        view.text = "Seznam osob je prazdny"
        view.textColor = scoutBlue
        view.isHidden = true
        view.textAlignment = .center
        view.translatesAutoresizingMaskIntoConstraints = false
        return view
    }()
    
    /// initialization function
    /// - Parameters:
    ///   - frame: frame
    ///   - style: table style
    override init(frame: CGRect, style: UITableView.Style) {
        super.init(frame: frame, style: style)
        register(OsobyTableViewCell.self, forCellReuseIdentifier: OsobyTableViewCell.reuseString)
        delegate = self
        dataSource = self
        setupConstraints()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /// function that sets up constraints for view
    private func setupConstraints() {
        addSubview(activityIndicator)
        addSubview(emptyLabel)
        tableFooterView = UIView()
        NSLayoutConstraint.activate([
            activityIndicator.centerXAnchor.constraint(equalTo: centerXAnchor),
            activityIndicator.centerYAnchor.constraint(equalTo: centerYAnchor),
            emptyLabel.centerYAnchor.constraint(equalTo: centerYAnchor),
            emptyLabel.centerXAnchor.constraint(equalTo: centerXAnchor)
        ])
    }
}

extension OsobyListView: UITableViewDelegate, UITableViewDataSource {
    
    /// function that returns number of table rows for given section
    /// - Parameters:
    ///   - tableView: table view
    ///   - section: section
    /// - Returns: number of rows
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        viewModel?.items.count ?? 0
    }
    
    /// function that returns table view cell for given path
    /// - Parameters:
    ///   - tableView: tableview
    ///   - indexPath: index path
    /// - Returns: table view cell for given path
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let item = viewModel?.items[indexPath.row],
            let cell = tableView.dequeueReusableCell(withIdentifier: OsobyTableViewCell.reuseString, for: indexPath) as? OsobyTableViewCell
                else { return UITableViewCell() }
        cell.title.text = item.DisplayName
        cell.phoneTitle.text = item.Phone.isEmpty ? nil : "+421 \(item.Phone)"
        cell.emailTitle.text = item.Email
        return cell
    }
    
    /// function that gets called when cell is selected
    /// - Parameters:
    ///   - tableView: tableview
    ///   - indexPath: index that was selected
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        guard let id = viewModel?.items[indexPath.row].ID else { return }
        viewDelegate?.selectedPerson(id: id)
    }
}
