//
//  SettingsViewController.swift
//  1Weather
//
//  Created by Dmitry Stepanets on 26.03.2021.
//

import UIKit

class SettingsViewController: UIViewController {
    //Private
    private let coordinator:SettingsCoordinator
    private let settingsCellFactory:SettingsCellFactory
    private let viewModel:SettingsViewModel
    private let tableView = UITableView(frame: .zero, style: .grouped)
    
    
    init(coordinator:SettingsCoordinator, settingsViewModel: SettingsViewModel) {
        self.coordinator = coordinator
        self.viewModel = settingsViewModel
        self.settingsCellFactory = SettingsCellFactory(viewModel: viewModel)
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        prepareController()
        prepareTableView()
        updateUI()
    }
    
    override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
        super.traitCollectionDidChange(previousTraitCollection)
        updateUI()
    }
    
    private func updateUI() {
        view.backgroundColor = ThemeManager.currentTheme.baseBackgroundColor
        tableView.backgroundColor = ThemeManager.currentTheme.baseBackgroundColor
    }
    
    @objc private func handleCloseButton() {
        self.dismiss(animated: true) {
            self.coordinator.viewControllerDidEnd(controller: self)
        }
    }
}

//MARK:- Prepare
private extension SettingsViewController {
    func prepareController() {
        navigationItem.title = "menu.settings".localized().capitalized
        let closeButton = UIBarButtonItem(title: "general.close".localized().capitalized,
                                          style: .done,
                                          target: self,
                                          action: #selector(handleCloseButton))
        navigationItem.leftBarButtonItem = closeButton
    }
    
    func prepareTableView() {
        settingsCellFactory.registerCells(on: tableView)
        tableView.separatorStyle = .none
        tableView.contentInset = .init(top: 0, left: 0, bottom: 24, right: 0)
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.dataSource = self
        tableView.delegate = self
        tableView.separatorStyle = .none
        tableView.tableFooterView = UIView()
        tableView.rowHeight = UITableView.automaticDimension
        tableView.estimatedRowHeight = UITableView.automaticDimension
        view.addSubview(tableView)
        
        tableView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
    }
}

//MARK:- UITableView Data Source
extension SettingsViewController: UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return settingsCellFactory.numberOfSections
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return settingsCellFactory.numberOfRows(inSection: section)
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        return settingsCellFactory.cellFromTableView(tableView: tableView, indexPath: indexPath)
    }
}

//MARK:- UITableView Delegate
extension SettingsViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let settingsSection = settingsCellFactory.sectionTypeAt(indexPath: [section, 0])
        let view = UIView()
        view.backgroundColor = ThemeManager.currentTheme.baseBackgroundColor
        
        switch settingsSection {
        case .theme, .units:
            let label = UILabel()
            label.text = settingsSection.localized
            label.font = AppFont.SFPro.bold(size: 18)
            label.textColor = view.interfaceStyle == .light ?
                ThemeManager.currentTheme.secondaryTextColor :
                ThemeManager.currentTheme.primaryTextColor
            view.addSubview(label)
            
            label.snp.makeConstraints { (make) in
                make.left.equalToSuperview().inset(24)
                make.bottom.equalToSuperview().inset(9)
            }
        default:
            break
        }
        
        return view
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return .leastNormalMagnitude
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return nil
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        switch settingsCellFactory.sectionTypeAt(indexPath: [section, 0]) {
        case .theme, .units:
            return 57
        default:
            return 24
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        coordinator.openDetailsViewController(rowType: settingsCellFactory.rowTypeAt(indexPath: indexPath))
    }
}
