//
//  PublicProvidentViewController.swift
//  Product Calculator
//
//  Created by Suraj Kumar Mandal on 06/12/21.
//

import UIKit
import SideMenu
import Toast_Swift

class PublicProvidentViewController: UIViewController {
    
    @IBOutlet var planningDateTF: UITextField!
    @IBOutlet var ppfDepositAmountTF: UITextField!
    @IBOutlet var amountDepositFrequencyTF: UITextField!
    @IBOutlet var depositStartDateTF: UITextField!
    @IBOutlet var annualInterestRateTF: UITextField!
    @IBOutlet var termYearsTF: UITextField!
    @IBOutlet var compoundFrequencyTF: UITextField!
    @IBOutlet var extensionTF: UITextField!
    @IBOutlet var extensionTypeLabel: UILabel!
    @IBOutlet var extensionTypeTF: UITextField!
    @IBOutlet var extensionDepositAmountLabel: UILabel!
    @IBOutlet var extensionDepositAmountTF: UITextField!
    @IBOutlet var extensionAmountDepositFrequencyLabel: UILabel!
    @IBOutlet var extensionAmountDepositFrequencyTF: UITextField!
    @IBOutlet var extensionAnnualInterestRateLabel: UILabel!
    @IBOutlet var extensionAnnualInterestRateTF: UITextField!
    @IBOutlet var extensionTermYearsLabel: UILabel!
    @IBOutlet var extensionTermYearsTF: UITextField!
    @IBOutlet var extensionCompoundFrequencyLabel: UILabel!
    @IBOutlet var extensionCompoundFrequencyTF: UITextField!
    
    fileprivate let customPicker = ToolbarPickerView()
    var activeTextField = 0
    var menu = Int()
    var isExtension = Bool()
    
    var viewModel = PublicProvidentViewModel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        viewModel.delegate = self
        
        planningDateTF.delegate = self
        ppfDepositAmountTF.delegate = self
        amountDepositFrequencyTF.delegate = self
        depositStartDateTF.delegate = self
        annualInterestRateTF.delegate = self
        termYearsTF.delegate = self
        compoundFrequencyTF.delegate = self
        extensionTF.delegate = self
        
        extensionTypeTF.delegate = self
        extensionDepositAmountTF.delegate = self
        extensionAmountDepositFrequencyTF.delegate = self
        extensionAnnualInterestRateTF.delegate = self
        extensionTermYearsTF.delegate = self
        extensionCompoundFrequencyTF.delegate = self
        
        isExtension = false
        extensionStatus()
    }
    
    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)
        
        //Date Picker
        depositStartDateTF.datePicker(target: self,
                                 doneAction: #selector(doneAction),
                                 cancelAction: #selector(cancelAction),
                                 datePickerMode: .date)
        depositStartDateTF.delegate = self
        
        //Picker View
        createPickerView()
        
        //Term in years
        termYearsTF.text = "15"
        compoundFrequencyTF.text = "Annually"
    }
    
    @objc func openMenu(_ sender: Any) {
        let menu = storyboard!.instantiateViewController(withIdentifier: "SideMenuNavigationController") as! SideMenuNavigationController
        present(menu, animated: true, completion: nil)
    }
    
    func createPickerView() {
        self.amountDepositFrequencyTF.inputView = self.customPicker
        self.amountDepositFrequencyTF.inputAccessoryView = self.customPicker.toolbar
        
        self.compoundFrequencyTF.inputView = self.customPicker
        self.compoundFrequencyTF.inputAccessoryView = self.customPicker.toolbar
        
        self.extensionTF.inputView = self.customPicker
        self.extensionTF.inputAccessoryView = self.customPicker.toolbar
        
        self.customPicker.delegate = self
        self.customPicker.dataSource = self
        self.customPicker.toolbarDelegate = self
    }
    
    @objc
    func cancelAction() {
        self.depositStartDateTF.resignFirstResponder()
    }
    
    @objc
    func doneAction() {
        if let datePickerView = self.depositStartDateTF.inputView as? UIDatePicker {
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = AppConstant.dateFormat2
            let dateString = dateFormatter.string(from: datePickerView.date)
            self.depositStartDateTF.text = dateString
            
            print(datePickerView.date)
            print(dateString)
            
            self.depositStartDateTF.resignFirstResponder()
            if Reachability.isConnectedToNetwork() {
                viewModel.getInterestRate(depositDate: dateString)
            } else {
                Alert.showInternetFailureAlert(on: self)
            }
        }
    }
    
    func dataValidationWithExtension() {
        if planningDateTF.text?.isEmpty == true {
            self.view.makeToast("Select deposit date!")
        } else if ppfDepositAmountTF.text?.isEmpty == true {
            self.view.makeToast("Select girl child age!")
        } else if amountDepositFrequencyTF.text?.isEmpty == true {
            self.view.makeToast("Fill deposit amount!")
        } else if depositStartDateTF.text?.isEmpty == true {
            self.view.makeToast("Select amount deposit frequency!")
        } else if annualInterestRateTF.text?.isEmpty == true {
            self.view.makeToast("Fill annual interest rate!")
        } else if termYearsTF.text?.isEmpty == true {
            self.view.makeToast("Select payment term in years!")
        } else if compoundFrequencyTF.text?.isEmpty == true {
            self.view.makeToast("Select maturity term in years!")
        } else if extensionTF.text?.isEmpty == true {
            self.view.makeToast("Select compound frequency!")
        } else {
            if Reachability.isConnectedToNetwork() {
                viewModel.getPPFExtOutput(depositAmount: ppfDepositAmountTF.text!, tenureType: "Y", tenure: termYearsTF.text!, rdDepositFreq: annualInterestRateTF.text!, compundingFreq: compoundFrequencyTF.text!, depositDate: depositStartDateTF.text!, totalAmountDiposited: ppfDepositAmountTF.text!)
            } else {
                Alert.showInternetFailureAlert(on: self)
            }
        }
    }
    
    func dataValidationWithoutExtension() {
        if planningDateTF.text?.isEmpty == true {
            self.view.makeToast("Select deposit date!")
        } else if ppfDepositAmountTF.text?.isEmpty == true {
            self.view.makeToast("Select girl child age!")
        } else if amountDepositFrequencyTF.text?.isEmpty == true {
            self.view.makeToast("Fill deposit amount!")
        } else if depositStartDateTF.text?.isEmpty == true {
            self.view.makeToast("Select amount deposit frequency!")
        } else if annualInterestRateTF.text?.isEmpty == true {
            self.view.makeToast("Fill annual interest rate!")
        } else if termYearsTF.text?.isEmpty == true {
            self.view.makeToast("Select payment term in years!")
        } else if compoundFrequencyTF.text?.isEmpty == true {
            self.view.makeToast("Select maturity term in years!")
        } else if extensionTF.text?.isEmpty == true {
            self.view.makeToast("Fill extension!")
        } else {
            if Reachability.isConnectedToNetwork() {
                viewModel.getPPFOutput(depositAmount: ppfDepositAmountTF.text!, tenureType: "Y", tenure: termYearsTF.text!, rdDepositFreq: amountDepositFrequencyTF.text!, compundingFreq: compoundFrequencyTF.text!, depositDate: depositStartDateTF.text!)
            } else {
                Alert.showInternetFailureAlert(on: self)
            }
        }
    }
    
    func extensionStatus() {
        //Extension type UI manage
        if isExtension == false {
            extensionTypeLabel.isHidden = true
            extensionTypeTF.isHidden = true
            extensionDepositAmountLabel.isHidden = true
            extensionDepositAmountTF.isHidden = true
            extensionAmountDepositFrequencyLabel.isHidden = true
            extensionAmountDepositFrequencyTF.isHidden = true
            extensionAnnualInterestRateLabel.isHidden = true
            extensionAnnualInterestRateTF.isHidden = true
            extensionTermYearsLabel.isHidden = true
            extensionTermYearsTF.isHidden = true
            extensionCompoundFrequencyLabel.isHidden = true
            extensionCompoundFrequencyTF.isHidden = true
        } else {
            extensionTypeLabel.isHidden = false
            extensionTypeTF.isHidden = false
            extensionDepositAmountLabel.isHidden = false
            extensionDepositAmountTF.isHidden = false
            extensionAmountDepositFrequencyLabel.isHidden = false
            extensionAmountDepositFrequencyTF.isHidden = false
            extensionAnnualInterestRateLabel.isHidden = false
            extensionAnnualInterestRateTF.isHidden = false
            extensionTermYearsLabel.isHidden = false
            extensionTermYearsTF.isHidden = false
            extensionCompoundFrequencyLabel.isHidden = false
            extensionCompoundFrequencyTF.isHidden = false
        }
    }
    
    
    /*
     // 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) {
        if isExtension == false {
            self.dataValidationWithoutExtension()
        } else {
            self.dataValidationWithExtension()
        }
    }
    
    @IBAction func undoAction(_ sender: Any) {
        ppfDepositAmountTF.text = nil
        amountDepositFrequencyTF.text = nil
        depositStartDateTF.text = nil
        //extensionTF.text = nil
    }
    
}

extension PublicProvidentViewController: 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.INTEREST_PAYOUT_FREQUENCY.count
        case 2:
            return AppConstant.INTEREST_PAYOUT_FREQUENCY.count
        case 3:
            return AppConstant.EXTENSION.count
        default:
            return 0
            
        }
    }
    
    func pickerView( _ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        switch activeTextField{
        case 1:
            return AppConstant.INTEREST_PAYOUT_FREQUENCY[row]
        case 2:
            return AppConstant.INTEREST_PAYOUT_FREQUENCY[row]
        case 3:
            return AppConstant.EXTENSION[row]
        default:
            return ""
        }
    }
    
    func pickerView( _ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        
        switch activeTextField{
        case 1:
            amountDepositFrequencyTF.text = AppConstant.INTEREST_PAYOUT_FREQUENCY[row]
            break
        case 2:
            compoundFrequencyTF.text = AppConstant.INTEREST_PAYOUT_FREQUENCY[row]
            break
        case 3:
            extensionTF.text = AppConstant.EXTENSION[row]
            break
        default:
            break
        }
    }
}

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

extension PublicProvidentViewController: ToolbarPickerViewDelegate {
    func didTapDone() {
        switch activeTextField {
        case 1:
            let row = self.customPicker.selectedRow(inComponent: 0)
            self.customPicker.selectRow(row, inComponent: 0, animated: false)
            self.amountDepositFrequencyTF.text = AppConstant.INTEREST_PAYOUT_FREQUENCY[row]
            self.amountDepositFrequencyTF.resignFirstResponder()
        case 2:
            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()
        case 3:
            let row = self.customPicker.selectedRow(inComponent: 0)
            self.customPicker.selectRow(row, inComponent: 0, animated: false)
            self.extensionTF.text = AppConstant.EXTENSION[row]
            if self.extensionTF.text == "Yes" {
                isExtension = true
                extensionStatus()
            } else {
                isExtension = false
                extensionStatus()
            }
            self.extensionTF.resignFirstResponder()
        default:
            return
        }
    }
    
    func didTapCancel() {
        switch activeTextField {
        case 1:
            self.amountDepositFrequencyTF.text = nil
            self.amountDepositFrequencyTF.resignFirstResponder()
        case 2:
            self.compoundFrequencyTF.text = nil
            self.compoundFrequencyTF.resignFirstResponder()
        case 3:
            self.extensionTF.text = nil
            self.extensionTF.resignFirstResponder()
        default:
            return
        }
    }
}

extension PublicProvidentViewController: PublicProvidentViewProtocol {
    func navigate(_ data: PublicProvidentModel) {
        DispatchQueue.main.async {
            let ppfSummaryVC = self.storyboard?.instantiateViewController(withIdentifier: "PPFSummaryViewController") as! PPFSummaryViewController
            ppfSummaryVC.ppfModel = data
            self.navigationController?.pushViewController(ppfSummaryVC, animated: true)
        }
    }
    
    func setInterestRate(rate: String) {
        annualInterestRateTF.text = rate
    }
    
    func startLoader() {
        ActivityIndicator.start()
    }
    
    func stopLoader() {
        ActivityIndicator.stop()
    }
    
    func showError(error: String) {
        self.view.makeToast(error)
    }
}
