//
//  SettingsRootViewController.swift
//  xDrip
//
//  Created by Artem Kalmykov on 11.03.2020.
//  Copyright (c) 2020 Faifly. All rights reserved.
//
//  This file was generated by the Clean Swift Xcode Templates so
//  you can apply clean architecture to your iOS and Mac projects,
//  see http://clean-swift.com
//

import UIKit

protocol SettingsRootDisplayLogic: AnyObject {
    func displayLoad(viewModel: SettingsRoot.Load.ViewModel)
}

class SettingsRootViewController: BaseSettingsViewController, SettingsRootDisplayLogic {
    var interactor: SettingsRootBusinessLogic?
    var router: SettingsRootDataPassing?
    
    // MARK: Object lifecycle
    
    required init() {
        super.init()
        setup()
    }
    
    @available(*, unavailable)
    required init?(coder: NSCoder) {
        fatalError("Use regular init")
    }
    
    // MARK: Setup
    
    private func setup() {
        let viewController = self
        let interactor = SettingsRootInteractor()
        let presenter = SettingsRootPresenter()
        let router = SettingsRootRouter()
        viewController.interactor = interactor
        viewController.router = router
        interactor.presenter = presenter
        interactor.router = router
        presenter.viewController = viewController
        router.viewController = viewController
        router.dataStore = interactor
    }
    
    // MARK: IB
    
    override var tableViewStyle: UITableView.Style {
        return UIDevice.current.userInterfaceIdiom == .pad ? .grouped : super.tableViewStyle
    }
    
    private var settingsChangeObservers: [NSObjectProtocol] = []
    
    // MARK: View lifecycle
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        setupNavigationItems()
        doLoad()
        
        settingsChangeObservers = NotificationCenter.default.subscribe(
            forSettingsChange: [.deviceMode, .injectionType],
            notificationHandler: doLoad
        )
    }
    
    // MARK: Do something
    
    private func doLoad() {
        let request = SettingsRoot.Load.Request()
        interactor?.doLoad(request: request)
    }
    
    private func setupUI() {
        title = "settings_root_title".localized
    }
    
    private func setupNavigationItems() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(
            title: "close".localized,
            style: .plain,
            target: self,
            action: #selector(onCancelButtonTap)
        )
    }
    
    @objc private func onCancelButtonTap() {
        let request = SettingsRoot.Cancel.Request()
        interactor?.doCancel(request: request)
    }
    
    // MARK: Display
    
    func displayLoad(viewModel: SettingsRoot.Load.ViewModel) {
        update(with: viewModel.tableViewModel)
    }
}
