//
//  TodayViewController.swift
//  1Weather
//
//  Created by Dmitry Stepanets on 08.02.2021.
//

import UIKit
import CoreLocation

class TodayViewController: UIViewController {
    //Private
    private let cityButton = NavigationCityButton()
    private let viewModel:TodayViewModel
    private let tableView = UITableView()
    private var localizationObserver:Any?
    
    deinit {
        if let observer = localizationObserver {
            NotificationCenter.default.removeObserver(observer)
        }
    }
    
    init(viewModel: TodayViewModel) {
        self.viewModel = viewModel
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        prepareViewController()
        prepareNavigationBar()
        prepareTableView()
        
        viewModel.delegate = self
        viewModel.updateWeather()
    }
   
    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        super.viewWillTransition(to: size, with: coordinator)
        
        coordinator.animate { _ in
            self.tableView.reloadData()
        }
    }
        
    @objc private func handleCityButton() {
        print("Handle city button")
    }
    
    @objc private func handleNotificationButton() {
        print("Handle notification button")
    }
}

private extension TodayViewController {
    func prepareViewController() {
        view.backgroundColor = ThemeManager.currentTheme.baseBackgroundColor
        
        localizationObserver = NotificationCenter.default.addObserver(forName: .localizationChange, object: nil, queue: .main, using: { _ in
            self.tableView.reloadData()
        })
    }
        
    func prepareNavigationBar() {
        //City button
        cityButton.isHidden = true
        cityButton.addTarget(self, action: #selector(handleCityButton), for: .touchUpInside)
        let cityBarItem = UIBarButtonItem(customView: cityButton)
        
        let barSpacer = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
        barSpacer.width = 18
        
        //Notification button
        let notificationButton = UIButton()
        notificationButton.frame = .init(origin: .zero, size: .init(width: 40, height: 40))
        notificationButton.setImage(UIImage(named: "bell"), for: .normal)
        notificationButton.tintColor = ThemeManager.currentTheme.primaryTextColor
        notificationButton.addTarget(self, action: #selector(handleNotificationButton), for: .touchUpInside)
        
        let notificationBarButton = UIBarButtonItem(customView: notificationButton)
        notificationButton.contentEdgeInsets = .init(top: 0, left: 16, bottom: 0, right: 0)
        self.navigationItem.leftBarButtonItems = [barSpacer, cityBarItem]
        self.navigationItem.rightBarButtonItem = notificationBarButton
    }
    
    func prepareTableView() {
        viewModel.todayCellFactory.registerCells(on: tableView)
        tableView.contentInset = .init(top: 0, left: 0, bottom: 15, right: 0)
        tableView.backgroundColor = ThemeManager.currentTheme.baseBackgroundColor
        tableView.separatorStyle = .none
        tableView.tableFooterView = UIView()
        tableView.estimatedRowHeight = UITableView.automaticDimension
        tableView.rowHeight = UITableView.automaticDimension
        tableView.delegate = self
        tableView.dataSource = self
        view.addSubview(tableView)
        
        tableView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
    }
}

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

//MARK:- UITableView Delegate
extension TodayViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let vc = UIViewController()
        vc.view.backgroundColor = .red
        navigationController?.pushViewController(vc, animated: true)
    }
    
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        viewModel.todayCellFactory.willDisplay(cell: cell)
    }
}

//MARK:- ViewModel Delegate
extension TodayViewController: ViewModelDelegate {
    func viewModelDidChange<P>(model: P) where P : ViewModelProtocol {
        cityButton.configure(with: viewModel.location)
        cityButton.isHidden = false
        tableView.reloadData()
    }
}
