//
//  EPFViewController.swift
//  Product Calculator
//
//  Created by Suraj Kumar Mandal on 08/12/21.
//

import UIKit
import SideMenu
import Toast_Swift

class EPFViewController: UIViewController {
    
    @IBOutlet var clientDobTF: UITextField!
    @IBOutlet var currentEpfBalanceTF: UITextField!
    @IBOutlet var currentEpsBalanceTF: UITextField!
    @IBOutlet var monthlyBasicTF: UITextField!
    @IBOutlet var expectedIncreaseSalaryTF: UITextField!
    @IBOutlet var expectedEpfoInterestRateTF: UITextField!
    @IBOutlet var contributionAgeTF: UITextField!
    @IBOutlet var epfWithdrawalAgeTF: UITextField!
    @IBOutlet var planningDateTF: UITextField!
    @IBOutlet var salaryIncreaseMonthTF: UITextField!
    
    fileprivate let customPicker = ToolbarPickerView()
    var activeTextField = 0
    var menu = Int()
    
    var viewModel = EPFViewModel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        viewModel.delegate = self
        
        clientDobTF.delegate = self
        currentEpfBalanceTF.delegate = self
        currentEpsBalanceTF.delegate = self
        monthlyBasicTF.delegate = self
        expectedIncreaseSalaryTF.delegate = self
        expectedEpfoInterestRateTF.delegate = self
        contributionAgeTF.delegate = self
        epfWithdrawalAgeTF.delegate = self
        planningDateTF.delegate = self
        salaryIncreaseMonthTF.delegate = self
        
        if Reachability.isConnectedToNetwork() {
            viewModel.getInterestRate()
            viewModel.getGrowthRate()
        } else {
            self.view.makeToast("Unable to connect to internet!")
        }
    }
    
    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
        }
        
        //Planning date set
        let date = Date()
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "dd-MM-yyyy"
        planningDateTF.text = dateFormatter.string(from: date)
        
        //Set salary increase month
        salaryIncreaseMonthTF.text = "Apr-16"
        
        //Date Picker
        clientDobTF.datePicker(target: self,
                                 doneAction: #selector(doneAction),
                                 cancelAction: #selector(cancelAction),
                                 datePickerMode: .date)
        clientDobTF.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.contributionAgeTF.inputView = self.customPicker
        self.contributionAgeTF.inputAccessoryView = self.customPicker.toolbar
        
        self.epfWithdrawalAgeTF.inputView = self.customPicker
        self.epfWithdrawalAgeTF.inputAccessoryView = self.customPicker.toolbar
        
        self.customPicker.delegate = self
        self.customPicker.dataSource = self
        self.customPicker.toolbarDelegate = self
    }
    
    @objc
    func cancelAction() {
        self.clientDobTF.resignFirstResponder()
    }
    
    @objc
    func doneAction() {
        if let datePickerView = self.clientDobTF.inputView as? UIDatePicker {
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = AppConstant.dateFormat2
            let dateString = dateFormatter.string(from: datePickerView.date)
            self.clientDobTF.text = dateString
            
            print(datePickerView.date)
            print(dateString)
            
            self.clientDobTF.resignFirstResponder()
        }
    }
    
    func dataValidation() {
        if clientDobTF.text?.isEmpty == true {
            self.view.makeToast("Select client date of birth!")
        } else if currentEpfBalanceTF.text?.isEmpty == true {
            self.view.makeToast("Enter current EPF balance!")
        } else if currentEpsBalanceTF.text?.isEmpty == true {
            self.view.makeToast("Enter current EPS balance!")
        } else if monthlyBasicTF.text?.isEmpty == true {
            self.view.makeToast("Enter monthly basic!")
        } else if expectedIncreaseSalaryTF.text?.isEmpty == true {
            self.view.makeToast("Enter expected increase in salary!")
        } else if expectedEpfoInterestRateTF.text?.isEmpty == true {
            self.view.makeToast("Enter expected EPFO interest rate!")
        } else if contributionAgeTF.text?.isEmpty == true {
            self.view.makeToast("Enter contribution upto age!")
        } else if epfWithdrawalAgeTF.text?.isEmpty == true {
            self.view.makeToast("Enter EPF withdrawal age!")
        } else if planningDateTF.text?.isEmpty == true {
            self.view.makeToast("Enter planning date!")
        } else if salaryIncreaseMonthTF.text?.isEmpty == true {
            self.view.makeToast("Enter salary increase month!")
        } else {
            if Reachability.isConnectedToNetwork() {
                let salaryIncrease = expectedIncreaseSalaryTF.text!
                let salaryPercent = Double(salaryIncrease)!/100.0
                
                viewModel.getEPFOutput(clientDOB: clientDobTF.text!, currEPFBal: currentEpfBalanceTF.text!, currEPSBal: currentEpsBalanceTF.text!, monthlyBasicDA: monthlyBasicTF.text!, expectedIncreaseSal: String(salaryPercent), contributionUptoAge: contributionAgeTF.text!, epfWithdrawAlage: epfWithdrawalAgeTF.text!, increaseMonth: salaryIncreaseMonthTF.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) {
        clientDobTF.text = nil
        currentEpfBalanceTF.text = nil
        currentEpsBalanceTF.text = nil
        monthlyBasicTF.text = nil
        contributionAgeTF.text = nil
        epfWithdrawalAgeTF.text = nil
    }
    
}

extension EPFViewController: UIPickerViewDelegate, UIPickerViewDataSource {
    // MARK: UIPickerView Delegation
    
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }
    
    func pickerView( _ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        switch activeTextField
        {
        case 1:
            return AppConstant.CONTRIBUTION_AGE.count
        case 2:
            return AppConstant.WITHDRAWAL_AGE.count
        default:
            return 0
            
        }
    }
    
    func pickerView( _ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        switch activeTextField{
        case 1:
            return AppConstant.CONTRIBUTION_AGE[row]
        case 2:
            return AppConstant.WITHDRAWAL_AGE[row]
        default:
            return ""
        }
    }
    
    func pickerView( _ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        
        switch activeTextField{
        case 1:
            contributionAgeTF.text = AppConstant.CONTRIBUTION_AGE[row]
            break
        case 2:
            epfWithdrawalAgeTF.text = AppConstant.WITHDRAWAL_AGE[row]
            break
        default:
            break
        }
    }
}

extension EPFViewController: UITextFieldDelegate {
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        switch textField {
        case contributionAgeTF:
            return false
        case epfWithdrawalAgeTF:
            return false
        default:
            return true
        }
    }
    
    // when user select a textfield, this method will be called
    func textFieldDidBeginEditing(_ textField: UITextField) {
        switch textField {
        case contributionAgeTF:
            activeTextField = 1
            customPicker.reloadAllComponents()
        case epfWithdrawalAgeTF:
            activeTextField = 2
            customPicker.reloadAllComponents()
        default:
            activeTextField = 0
        }
    }
}

extension EPFViewController: ToolbarPickerViewDelegate {
    func didTapDone() {
        switch activeTextField {
        case 1:
            let row = self.customPicker.selectedRow(inComponent: 0)
            self.customPicker.selectRow(row, inComponent: 0, animated: false)
            self.contributionAgeTF.text = AppConstant.CONTRIBUTION_AGE[row]
            self.contributionAgeTF.resignFirstResponder()
        case 2:
            let row = self.customPicker.selectedRow(inComponent: 0)
            self.customPicker.selectRow(row, inComponent: 0, animated: false)
            self.epfWithdrawalAgeTF.text = AppConstant.WITHDRAWAL_AGE[row]
            self.epfWithdrawalAgeTF.resignFirstResponder()
        default:
            return
        }
    }
    
    func didTapCancel() {
        switch activeTextField {
        case 1:
            self.contributionAgeTF.text = nil
            self.contributionAgeTF.resignFirstResponder()
        case 2:
            self.epfWithdrawalAgeTF.text = nil
            self.epfWithdrawalAgeTF.resignFirstResponder()
        default:
            return
        }
    }
}

extension EPFViewController: EPFViewProtocol {
    func setGrowthRate(rate: String) {
        let growthRate = Double(rate)!*100
        expectedIncreaseSalaryTF.text = String(growthRate)
    }
    
    func navigate(_ data: EPFModel) {
        DispatchQueue.main.async {
            let epfSummaryVC = self.storyboard?.instantiateViewController(withIdentifier: "EPFSummaryViewController") as! EPFSummaryViewController
            epfSummaryVC.epfModel = data
            self.navigationController?.pushViewController(epfSummaryVC, animated: true)
        }
    }
    
    func setInterestRate(rate: String) {
        let interestRate = Double(rate)!*100
        expectedEpfoInterestRateTF.text = String(interestRate)
    }
    
    func startLoader() {
        ActivityIndicator.start()
    }
    
    func stopLoader() {
        ActivityIndicator.stop()
    }
    
    func showError(error: String) {
        self.view.makeToast(error)
    }
}
