//
//  CpCdViewController.swift
//  Product Calculator
//
//  Created by Suraj Kumar Mandal on 29/11/21.
//

import UIKit
import SideMenu
import Toast_Swift

class CpCdViewController: UIViewController {
    
    @IBOutlet var investmentAmountTF: UITextFieldWithDoneButton!
    @IBOutlet var annualInterestRateTF: UITextFieldWithDoneButton!
    @IBOutlet var tenureTF: UITextFieldWithDoneButton!
    @IBOutlet var compoundFrequencyTF: UITextField!
    @IBOutlet var investmentDateTF: UITextField!
    
    fileprivate let customPicker = ToolbarPickerView()
    var menu = Int()
    
    var viewModel = CpCdViewModel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        viewModel.delegate = self
        
        investmentAmountTF.delegate = self
        annualInterestRateTF.delegate = self
        tenureTF.delegate = self
        compoundFrequencyTF.delegate = self
        investmentDateTF.delegate = self
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        navigationController?.navigationBar.barStyle = .black
        setupUI()
    }
    
    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }
    
    func setupUI() {
        self.navigationItem.title = AppConstant.MENU_TITLE[menu]
        self.navigationItem.hidesBackButton = true
        let menuBarButtonItem = UIBarButtonItem(image: UIImage(systemName: "line.3.horizontal"), style: .plain, target: self, action: #selector(openMenu))
        self.navigationItem.leftBarButtonItem  = menuBarButtonItem
        if #available(iOS 13, *) {
            let appearance = UINavigationBarAppearance()
            appearance.backgroundColor = .systemBlue
            appearance.titleTextAttributes = [.foregroundColor: UIColor.white]
            appearance.largeTitleTextAttributes = [.foregroundColor: UIColor.white]
            
            navigationController?.navigationBar.tintColor = .white
            navigationController?.navigationBar.standardAppearance = appearance
            navigationController?.navigationBar.compactAppearance = appearance
            navigationController?.navigationBar.scrollEdgeAppearance = appearance
        }
        
        //Date Picker
        investmentDateTF.datePicker(target: self,
                                 doneAction: #selector(doneAction),
                                 cancelAction: #selector(cancelAction),
                                 datePickerMode: .date)
        investmentDateTF.delegate = self
        
        //Picker View
        createPickerView()
    }
    
    @objc func openMenu(_ sender: Any) {
        let menu = storyboard!.instantiateViewController(withIdentifier: "SideMenuNavigationController") as! SideMenuNavigationController
        present(menu, animated: true, completion: nil)
    }
    
    func createPickerView() {
        self.compoundFrequencyTF.inputView = self.customPicker
        self.compoundFrequencyTF.inputAccessoryView = self.customPicker.toolbar
        
        self.customPicker.delegate = self
        self.customPicker.dataSource = self
        self.customPicker.toolbarDelegate = self
    }
    
    @objc
    func cancelAction() {
        self.investmentDateTF.resignFirstResponder()
    }
    
    @objc
    func doneAction() {
        if let datePickerView = self.investmentDateTF.inputView as? UIDatePicker {
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = AppConstant.dateFormat1
            let dateString = dateFormatter.string(from: datePickerView.date)
            self.investmentDateTF.text = dateString
            //self.dateOfBirth = dateString
            
            print(datePickerView.date)
            print(dateString)
            
            self.investmentDateTF.resignFirstResponder()
        }
    }
    
    func dataValidation() {
        if investmentAmountTF.text?.isEmpty == true {
            self.view.makeToast("Fill investment amount!")
        } else if annualInterestRateTF.text?.isEmpty == true {
            self.view.makeToast("Fill annual interest rate!")
        } else if tenureTF.text?.isEmpty == true {
            self.view.makeToast("Fill tenture in days!")
        } else if compoundFrequencyTF.text?.isEmpty == true {
            self.view.makeToast("Select compound frequency!")
        } else if investmentDateTF.text?.isEmpty == true {
            self.view.makeToast("Select investment date!")
        } else {
            if Reachability.isConnectedToNetwork() {
                let interest = annualInterestRateTF.text!
                let interestPercent = Double(interest)!/100.0
                
                viewModel.getCpCdOutput(depositAmount: investmentAmountTF.text!, annualInterest: String(interestPercent), tenure: tenureTF.text!, compoundFrequency: compoundFrequencyTF.text!, depositDate: investmentDateTF.text!)
            } else {
                Alert.showInternetFailureAlert(on: self)
            }
        }
    }
    
    
    /*
     // MARK: - Navigation
     
     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
     // Get the new view controller using segue.destination.
     // Pass the selected object to the new view controller.
     }
     */
    
    @IBAction func saveAction(_ sender: Any) {
        self.dataValidation()
    }
    
    @IBAction func undoAction(_ sender: Any) {
        investmentAmountTF.text = nil
        annualInterestRateTF.text = nil
        tenureTF.text = nil
        compoundFrequencyTF.text = nil
        investmentDateTF.text = nil
    }
    
}

extension CpCdViewController: UIPickerViewDelegate, UIPickerViewDataSource {
    // MARK: UIPickerView Delegation
    
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }
    
    func pickerView( _ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return AppConstant.INTEREST_PAYOUT_FREQUENCY.count
    }
    
    func pickerView( _ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return AppConstant.INTEREST_PAYOUT_FREQUENCY[row]
    }
    
    func pickerView( _ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        compoundFrequencyTF.text = AppConstant.INTEREST_PAYOUT_FREQUENCY[row]
    }
}

extension CpCdViewController: UITextFieldDelegate {
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        switch textField {
        case compoundFrequencyTF:
            return false
        default:
            return true
        }
    }
    
    // when user select a textfield, this method will be called
    func textFieldDidBeginEditing(_ textField: UITextField) {
        switch textField {
        case compoundFrequencyTF:
            customPicker.reloadAllComponents()
        default:
            break
        }
    }
}

extension CpCdViewController: ToolbarPickerViewDelegate {
    func didTapDone() {
        let row = self.customPicker.selectedRow(inComponent: 0)
        self.customPicker.selectRow(row, inComponent: 0, animated: false)
        self.compoundFrequencyTF.text = AppConstant.INTEREST_PAYOUT_FREQUENCY[row]
        self.compoundFrequencyTF.resignFirstResponder()
    }
    
    func didTapCancel() {
        self.compoundFrequencyTF.text = nil
        self.compoundFrequencyTF.resignFirstResponder()
    }
}

extension CpCdViewController: CpCdViewProtocol {
    func navigate(_ data: CpCdModel) {
        DispatchQueue.main.async {
            let cpcdSummaryVC = self.storyboard?.instantiateViewController(withIdentifier: "CpCdSummaryViewController") as! CpCdSummaryViewController
            cpcdSummaryVC.cpcdModel = data
            self.navigationController?.pushViewController(cpcdSummaryVC, animated: true)
        }
    }
    
    func startLoader() {
        ActivityIndicator.start()
    }
    
    func stopLoader() {
        ActivityIndicator.stop()
    }
    
    func showError(error: String) {
        self.view.makeToast(error)
    }
}
