import UIKit
import Charts

/// registration view
class RegistraceView: UITableView {
    var viewModel: RegistraceViewModelProtocol? {
        didSet {
            guard let viewModel = viewModel else { return }
            if viewModel.loading {
                activityIndicator.startAnimating()
            } else {
                activityIndicator.stopAnimating()
            }
            headerView.subtitle.text = viewModel.currentYear.Year
            reloadData()
        }
    }
    
    private let activityIndicator: UIActivityIndicatorView = {
        let view = UIActivityIndicatorView()
        view.translatesAutoresizingMaskIntoConstraints = false
        view.style = .large
        view.color = scoutBlue
        view.startAnimating()
        return view
    }()
    
    let headerView: RegistraceHeaderView = {
        let view = RegistraceHeaderView()
        view.frame.size.height = 50
        return view
    }()
    
    /// initialization function
    /// - Parameters:
    ///   - frame: freame
    ///   - style: style for table
    override init(frame: CGRect, style: UITableView.Style) {
        super.init(frame: frame, style: .insetGrouped)
        addSubview(activityIndicator)
        delegate = self
        dataSource = self
        tableHeaderView = headerView
        tableFooterView = UIView()
        register(OsobaTableViewCell.self, forCellReuseIdentifier: OsobaTableViewCell.cellIdentifier)
        register(RegistraceMembersTableViewCell.self, forCellReuseIdentifier: RegistraceMembersTableViewCell.cellIdentifier)
        setupConstraints()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /// function that sets up the constraints for view
    private func setupConstraints() {
        NSLayoutConstraint.activate([
            activityIndicator.centerYAnchor.constraint(equalTo: centerYAnchor),
            activityIndicator.centerXAnchor.constraint(equalTo: centerXAnchor)
        ])
    }
}

extension RegistraceView: UITableViewDelegate, UITableViewDataSource {
    
    /// function that return number of sections
    /// - Parameter tableView: tableview
    /// - Returns: number of sections
    func numberOfSections(in tableView: UITableView) -> Int {
        4
    }
    
    /// 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 {
        switch section {
        case 0:
            return viewModel?.podrizeneJednotky.count ?? 0
        case 1:
            return viewModel?.registrovaneCleny.count ?? 0
        case 2:
            return viewModel?.vychovneStruktury.count ?? 0
        case 3:
            return viewModel?.vekoveStruktury.count ?? 0
        default:
            return 0
        }
    }
    
    /// function that returns view for header in given section
    /// - Parameters:
    ///   - tableView: tableview
    ///   - section: section
    /// - Returns: height for view in given section
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = RegistraceSectionHeaderView()
        switch section {
        case 0:
            view.title.text = "Podřízené jednotky"
            if viewModel?.podrizeneJednotky.count == 0 {
                view.subtitle.text = "Nepodařilo se získat data pro statistiky členů"
            }
        case 1:
            view.title.text = "Počty registrovaných členů"
            if viewModel?.registrovaneCleny.count == 0 {
                view.subtitle.text = "Nepodařilo se získat data pro statistiky členů"
            }
        case 2:
            view.title.text = "Počty členů podle výchovné struktúry"
            if viewModel?.vychovneStruktury.count == 0 {
                view.subtitle.text = "Nepodařilo se získat data pro statistiky členů"
            }
        case 3:
            view.title.text = "Počty členů podle vekové struktúry"
            if viewModel?.vekoveStruktury.count == 0 {
                view.subtitle.text = "Nepodařilo se získat data pro statistiky členů"
            }
        default:
            break
        }
        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 {
        switch section {
        case 0:
            if viewModel?.podrizeneJednotky.count != 0 {
                return 200
            }
        case 1:
            if viewModel?.registrovaneCleny.count != 0 {
                return 200
            }
        case 2:
            if viewModel?.vychovneStruktury.count != 0 {
                return 200
            }
        case 3:
            if viewModel?.vekoveStruktury.count != 0 {
                return 200
            }
        default:
            break
        }
        return 10
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        switch section {
        case 0:
            if viewModel?.podrizeneJednotky.count ?? 0 > 0 {
                let view = RegistraceSectionFooterView()
                view.addEntries(entries: viewModel?.getEntriesForJedontky())
                return view
            }
        case 1:
            if viewModel?.registrovaneCleny.count ?? 0 > 0 {
                let view = RegistraceSectionFooterView()
                view.addEntries(entries: viewModel?.getEntriesForRegistrovaneCleny())
                return view
            }
        case 2:
            if viewModel?.vychovneStruktury.count ?? 0 > 0 {
                let view = RegistraceSectionFooterView()
                view.addEntries(entries: viewModel?.getEntriesForVychovneStruktury())
                return view
            }
        case 3:
            if viewModel?.vekoveStruktury.count ?? 0 > 0 {
                let view = RegistraceSectionFooterView()
                view.addEntries(entries: viewModel?.getEntriesForVekoveStruktury())
                return view
            }
        default:
            break
        }
        return UIView()
    }
    
    /// 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 {
        switch indexPath.section {
        case 0:
            guard let item = viewModel?.podrizeneJednotky[indexPath.row] ,
            let cell = tableView.dequeueReusableCell(withIdentifier: OsobaTableViewCell.cellIdentifier) as? OsobaTableViewCell else { return UITableViewCell() }
            cell.title.text = item.UnitType
            cell.subtitle.text = item.Count
            return cell
        case 1:
            guard let item = viewModel?.registrovaneCleny[indexPath.row] ,
            let cell = tableView.dequeueReusableCell(withIdentifier: OsobaTableViewCell.cellIdentifier) as? OsobaTableViewCell else { return UITableViewCell() }
            cell.title.text = item.DisplayName
            cell.subtitle.text = item.Count
            return cell
        case 2:
            guard let item = viewModel?.vychovneStruktury[indexPath.row] ,
            let cell = tableView.dequeueReusableCell(withIdentifier: RegistraceMembersTableViewCell.cellIdentifier) as? RegistraceMembersTableViewCell else { return UITableViewCell() }
            cell.title.text = item.displayName
            cell.firstSubtitle.text = "\(item.items.members)"
            cell.secondSubtitle.text = "\(item.items.fHmembers)"
            return cell
        case 3:
            guard let item = viewModel?.vekoveStruktury[indexPath.row] ,
            let cell = tableView.dequeueReusableCell(withIdentifier: RegistraceMembersTableViewCell.cellIdentifier) as? RegistraceMembersTableViewCell else { return UITableViewCell() }
            cell.title.text = item.displayName
            cell.firstSubtitle.text = "\(item.items.members)"
            cell.secondSubtitle.text = "\(item.items.fHmembers)"
            return cell
        default:
            break
        }
        return UITableViewCell()
    }
    
    /// function that gets called when cell is selected
    /// - Parameters:
    ///   - tableView: tableview
    ///   - indexPath: index that was selected
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        deselectRow(at: indexPath, animated: true)
    }
}
