import UIKit

/// person detail view
class OsobaView: UIView {
    var viewModel: OsobaViewModel? {
        didSet {
            guard let viewModel = viewModel else { return }
            if viewModel.loading {
                activityIndicator.startAnimating()
            } else {
                activityIndicator.stopAnimating()
            }
            headerView.nameTitle.text = viewModel.detail?.FullName
            headerView.emailTitle.text = viewModel.detail?.Email
            headerView.phoneTitle.text = viewModel.getMainPhone()
            headerView.profilePicture.image = viewModel.getPhoto()
            tableView.reloadData()
        }
    }
    
    private let activityIndicator: UIActivityIndicatorView = {
        let view = UIActivityIndicatorView()
        view.translatesAutoresizingMaskIntoConstraints = false
        view.style = .large
        view.color = scoutBlue
        view.startAnimating()
        return view
    }()
    
    private let tableView: UITableView = {
        let view = UITableView(frame: .zero, style: .insetGrouped)
        view.translatesAutoresizingMaskIntoConstraints = false
        view.tableFooterView = UIView()
        view.rowHeight = UITableView.automaticDimension
        return view
    }()
    
    private let headerView: OsobaHeaderView = {
        let view = OsobaHeaderView()
        view.frame.size.height = 120
        return view
    }()
    
    /// initialization function
    /// - Parameter frame: frame
    override init(frame: CGRect) {
        super.init(frame: frame)
        addSubview(activityIndicator)
        addSubview(tableView)
        tableView.tableHeaderView = headerView
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(OsobaTableViewCell.self, forCellReuseIdentifier: OsobaTableViewCell.cellIdentifier)
        setupConstraints()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /// function for setting up constraints
    private func setupConstraints() {
        NSLayoutConstraint.activate([
            activityIndicator.centerYAnchor.constraint(equalTo: centerYAnchor),
            activityIndicator.centerXAnchor.constraint(equalTo: centerXAnchor),
            
            tableView.topAnchor.constraint(equalTo: topAnchor),
            tableView.leadingAnchor.constraint(equalTo: leadingAnchor),
            tableView.trailingAnchor.constraint(equalTo: trailingAnchor),
            tableView.bottomAnchor.constraint(equalTo: bottomAnchor),
        ])
    }
    
}

extension OsobaView: UITableViewDelegate, UITableViewDataSource {
    
    /// function that return number of sections
    /// - Parameter tableView: tableview
    /// - Returns: number of sections
    func numberOfSections(in tableView: UITableView) -> Int {
        viewModel?.sections.count ?? 0
    }
    
    /// function that returns header view for section
    /// - Parameters:
    ///   - tableView: tableview
    ///   - section: section
    /// - Returns: header view for section
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = OsobaSectionHeader()
        switch viewModel?.sections[section].first {
        case is Address:
            view.title.text = "Trvalé Bydliště"
        case is Contact:
            view.title.text = "Kontakty Osoby"
        case is Qualification:
            view.title.text = "Výpis Kvalifikací"
        case is Function:
            view.title.text = "Činovnické Funkce"
        case is Membership:
            view.title.text = "Členem v Jednotkách"
        case is Offer:
            view.title.text = "Nabídky vzdělání"
        default:
            return UIView()
        }
        return view
    }
    
    /// function that returns the height for footer in section
    /// - Parameters:
    ///   - tableView: tableview
    ///   - section: section
    /// - Returns: height of footer view for section
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        0
    }
    
    /// function that returns height for header based on section
    /// - Parameters:
    ///   - tableView: tableview
    ///   - section: section
    /// - Returns: heaight for header section
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        guard let items = viewModel?.sections[section] else { return 0 }
        if items.count == 0 {
            return 0
        } else {
            return 30
        }
    }
    
    /// 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?.sections[section].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?.sections[indexPath.section][indexPath.row],
            let cell = tableView.dequeueReusableCell(withIdentifier: OsobaTableViewCell.cellIdentifier) as? OsobaTableViewCell else { return UITableViewCell() }
        
        switch item {
        case let info as Address:
            cell.title.text = info.AddressType
            cell.subtitle.text = info.Value
        case let info as Contact:
            cell.title.text = info.ContactType
            cell.subtitle.text = viewModel?.getPhone(item: info)
        case let info as Qualification:
            let qCell = UITableViewCell()
            qCell.textLabel?.text = info.QualificationType
            return qCell
        case let info as Function:
            cell.title.text = info.Unit
            cell.subtitle.text = info.FunctionType
        case let info as Membership:
            cell.title.text = info.Unit
            cell.subtitle.text = info.MembershipType
        case let info as Offer:
            cell.title.text = info.OfferType
            cell.subtitle.text = nil
        default:
            break
        }
        
        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)
    }
}
