//
//  FixedDepositViewController.swift
//  Product Calculator
//
//  Created by Suraj Kumar Mandal on 15/11/21.
//

import UIKit
import SideMenu
import Toast_Swift

class FixedDepositViewController: UIViewController {
    
    @IBOutlet var depositAmountTF: UITextField!
    @IBOutlet var interestRateTF: UITextField!
    @IBOutlet var depositTypeTF: UITextField!
    @IBOutlet var termTF: UITextField!
    @IBOutlet var daysTF: UITextField!
    @IBOutlet var interestPayoutTF: UITextField!
    @IBOutlet var depositDateTF: UITextField!
    
    fileprivate let customPicker = ToolbarPickerView()
    var activeTextField = 0
    var menu = Int()
    
    var viewModel = FixedDepositViewModel()

    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        viewModel.delegate = self
        
        depositAmountTF.delegate = self
        interestRateTF.delegate = self
        depositTypeTF.delegate = self
        termTF.delegate = self
        daysTF.delegate = self
        interestPayoutTF.delegate = self
        depositDateTF.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
        depositDateTF.datePicker(target: self,
                         doneAction: #selector(doneAction),
                         cancelAction: #selector(cancelAction),
                         datePickerMode: .date)
        depositDateTF.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.depositTypeTF.inputView = self.customPicker
        self.depositTypeTF.inputAccessoryView = self.customPicker.toolbar
        
        self.termTF.inputView = self.customPicker
        self.termTF.inputAccessoryView = self.customPicker.toolbar
        
        self.interestPayoutTF.inputView = self.customPicker
        self.interestPayoutTF.inputAccessoryView = self.customPicker.toolbar
        
        self.customPicker.delegate = self
        self.customPicker.dataSource = self
        self.customPicker.toolbarDelegate = self
    }
    
    @objc
    func cancelAction() {
        self.depositDateTF.resignFirstResponder()
    }
    
    @objc
    func doneAction() {
        if let datePickerView = self.depositDateTF.inputView as? UIDatePicker {
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = AppConstant.dateFormat1
            let dateString = dateFormatter.string(from: datePickerView.date)
            self.depositDateTF.text = dateString
            //self.dateOfBirth = dateString
            
            print(datePickerView.date)
            print(dateString)
            
            self.depositDateTF.resignFirstResponder()
        }
    }
    
    func dataValidation() {
        if depositAmountTF.text?.isEmpty == true {
            self.view.makeToast("Fill deposit amount!")
        } else if interestRateTF.text?.isEmpty == true {
            self.view.makeToast("Fill annual interest rate!")
        } else if depositTypeTF.text?.isEmpty == true {
            self.view.makeToast("Select deposit type!")
        } else if termTF.text?.isEmpty == true {
            self.view.makeToast("Select term!")
        } else if daysTF.text?.isEmpty == true {
            self.view.makeToast("Fill no. of days/year!")
        } else if interestPayoutTF.text?.isEmpty == true {
            self.view.makeToast("Select interest payout frequency!")
        } else if depositDateTF.text?.isEmpty == true {
            self.view.makeToast("Select deposit date!")
        } else {
            if Reachability.isConnectedToNetwork() {
                if depositTypeTF.text == "Bank FD TDR" {
                    let interest = interestRateTF.text!
                    let interestRate = Double(interest)!/100.0
                    viewModel.getBankFDTDRDetails(depositAmount: depositAmountTF.text ?? "", annualInterest: String(format: "%.2f", interestRate), termYearsDays: termTF.text ?? "", tenure: daysTF.text ?? "", payoutFrq: interestPayoutTF.text ?? "", depositDate: depositDateTF.text ?? "")
                } else {
                    let interest = interestRateTF.text!
                    let interestRate = Double(interest)!/100.0
                    viewModel.getBankFDSTDRCDCPOutputList(depositAmount: depositAmountTF.text ?? "", annualInterest: String(format: "%.2f", interestRate), termYearsDays: termTF.text ?? "", tenure: daysTF.text ?? "", compoundFrequency: interestPayoutTF.text ?? "", depositDate: depositDateTF.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) {
        depositAmountTF.text = nil
        interestRateTF.text = nil
        depositTypeTF.text = nil
        termTF.text = nil
        daysTF.text = nil
        interestPayoutTF.text = nil
        depositDateTF.text = nil
    }
    
}

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

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

extension FixedDepositViewController: ToolbarPickerViewDelegate {
    func didTapDone() {
        switch activeTextField {
        case 1:
            let row = self.customPicker.selectedRow(inComponent: 0)
            self.customPicker.selectRow(row, inComponent: 0, animated: false)
            self.depositTypeTF.text = AppConstant.DEPOSIT_TYPE[row]
            self.depositTypeTF.resignFirstResponder()
        case 2:
            let row = self.customPicker.selectedRow(inComponent: 0)
            self.customPicker.selectRow(row, inComponent: 0, animated: false)
            self.termTF.text = AppConstant.FIXED_DEPOSIT_TERM[row]
            self.termTF.resignFirstResponder()
        case 3:
            let row = self.customPicker.selectedRow(inComponent: 0)
            self.customPicker.selectRow(row, inComponent: 0, animated: false)
            self.interestPayoutTF.text = AppConstant.INTEREST_PAYOUT_FREQUENCY[row]
            self.interestPayoutTF.resignFirstResponder()
        default:
            return
        }
    }
    
    func didTapCancel() {
        switch activeTextField {
        case 1:
            self.depositTypeTF.text = nil
            self.depositTypeTF.resignFirstResponder()
        case 2:
            self.termTF.text = nil
            self.termTF.resignFirstResponder()
        case 3:
            self.interestPayoutTF.text = nil
            self.interestPayoutTF.resignFirstResponder()
        default:
            return
        }
    }
}

extension FixedDepositViewController: FixedDepositViewProtocol {
    func navigateWithFDTDR(_ data:FDTDRDetailsModel) {
        DispatchQueue.main.async {
            let fdTDRSummaryVC = self.storyboard?.instantiateViewController(withIdentifier: "FixedDepositSummaryViewController") as! FixedDepositSummaryViewController
            fdTDRSummaryVC.fdtdrDetails = data
            fdTDRSummaryVC.fdType = "FDTDR"
            self.navigationController?.pushViewController(fdTDRSummaryVC, animated: true)
        }
    }
    
    func navigateWithFDSTDR(_ data:FDSTDRDetailsModel) {
        DispatchQueue.main.async {
            let fdSTDRSummaryVC = self.storyboard?.instantiateViewController(withIdentifier: "FixedDepositSummaryViewController") as! FixedDepositSummaryViewController
            fdSTDRSummaryVC.fdStdrDetails = data
            fdSTDRSummaryVC.fdType = "FDSTDR"
            self.navigationController?.pushViewController(fdSTDRSummaryVC, animated: true)
        }
    }
    
    func startLoader() {
        ActivityIndicator.start()
    }
    
    func stopLoader() {
        ActivityIndicator.stop()
    }
    
    func showError(error: String) {
        self.view.makeToast(error)
    }
}
