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

import UIKit
import SideMenu
import Toast_Swift

class BankRecurringViewController: UIViewController {
    
    @IBOutlet var depositAmountTF: UITextField!
    @IBOutlet var annualInterestRateTF: UITextField!
    @IBOutlet var amountDepositFrequencyTF: UITextField!
    @IBOutlet var termYearTF: UITextField!
    @IBOutlet var termMonthTF: UITextField!
    @IBOutlet var compoundFrequencyTF: UITextField!
    @IBOutlet var depositDateTF: UITextField!
    
    fileprivate let customPicker = ToolbarPickerView()
    var activeTextField = 0
    var menu = Int()
    
    var viewModel = BankRecurringViewModel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        viewModel.delegate = self
        
        depositAmountTF.delegate = self
        annualInterestRateTF.delegate = self
        amountDepositFrequencyTF.delegate = self
        termYearTF.delegate = self
        termMonthTF.delegate = self
        compoundFrequencyTF.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.amountDepositFrequencyTF.inputView = self.customPicker
        self.amountDepositFrequencyTF.inputAccessoryView = self.customPicker.toolbar
        
        self.termYearTF.inputView = self.customPicker
        self.termYearTF.inputAccessoryView = self.customPicker.toolbar
        
        self.termMonthTF.inputView = self.customPicker
        self.termMonthTF.inputAccessoryView = self.customPicker.toolbar
        
        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.depositDateTF.resignFirstResponder()
    }
    
    @objc
    func doneAction() {
        if let datePickerView = self.depositDateTF.inputView as? UIDatePicker {
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = AppConstant.dateFormat2
            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 annualInterestRateTF.text?.isEmpty == true {
            self.view.makeToast("Fill annual interest rate!")
        } else if amountDepositFrequencyTF.text?.isEmpty == true {
            self.view.makeToast("Select amount deposit frequency!")
        } else if termYearTF.text?.isEmpty == true {
            self.view.makeToast("Select term year!")
        } else if termMonthTF.text?.isEmpty == true {
            self.view.makeToast("Select term month!")
        } else if compoundFrequencyTF.text?.isEmpty == true {
            self.view.makeToast("Select compound frequency!")
        } else if depositDateTF.text?.isEmpty == true {
            self.view.makeToast("Select deposit date!")
        } else {
            if Reachability.isConnectedToNetwork() {
                let interest = annualInterestRateTF.text!
                let interestRate = Double(interest)!/100.0
                viewModel.getRecurringDeposit(depositAmount: depositAmountTF.text!, annualInterestRate: String(interestRate), year: termYearTF.text!, month: termMonthTF.text!, amountDepositFrequency: amountDepositFrequencyTF.text!, compoundFrequency: compoundFrequencyTF.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
        annualInterestRateTF.text = nil
        amountDepositFrequencyTF.text = nil
        termYearTF.text = nil
        termMonthTF.text = nil
        compoundFrequencyTF.text = nil
        depositDateTF.text = nil
    }
    
}

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

extension BankRecurringViewController: UITextFieldDelegate {
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        switch textField {
        case amountDepositFrequencyTF:
            return false
        case termYearTF:
            return false
        case termMonthTF:
            return false
        case compoundFrequencyTF:
            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 amountDepositFrequencyTF:
            activeTextField = 1
            customPicker.reloadAllComponents()
        case termYearTF:
            activeTextField = 2
            customPicker.reloadAllComponents()
        case termMonthTF:
            activeTextField = 3
            customPicker.reloadAllComponents()
        case compoundFrequencyTF:
            activeTextField = 4
            customPicker.reloadAllComponents()
        default:
            activeTextField = 0
        }
    }
}

extension BankRecurringViewController: 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.AMOUNT_DEPOSIT_FREQUENCY[row]
            self.amountDepositFrequencyTF.resignFirstResponder()
        case 2:
            let row = self.customPicker.selectedRow(inComponent: 0)
            self.customPicker.selectRow(row, inComponent: 0, animated: false)
            self.termYearTF.text = AppConstant.TERM_YEARS[row]
            self.termYearTF.resignFirstResponder()
        case 3:
            let row = self.customPicker.selectedRow(inComponent: 0)
            self.customPicker.selectRow(row, inComponent: 0, animated: false)
            self.termMonthTF.text = AppConstant.TERM_MONTHS[row]
            self.termMonthTF.resignFirstResponder()
        case 4:
            let row = self.customPicker.selectedRow(inComponent: 0)
            self.customPicker.selectRow(row, inComponent: 0, animated: false)
            self.compoundFrequencyTF.text = AppConstant.COMPOUND_FREQUENCY[row]
            self.compoundFrequencyTF.resignFirstResponder()
        default:
            return
        }
    }
    
    func didTapCancel() {
        switch activeTextField {
        case 1:
            self.amountDepositFrequencyTF.text = nil
            self.amountDepositFrequencyTF.resignFirstResponder()
        case 2:
            self.termYearTF.text = nil
            self.termYearTF.resignFirstResponder()
        case 3:
            self.termMonthTF.text = nil
            self.termMonthTF.resignFirstResponder()
        case 4:
            self.compoundFrequencyTF.text = nil
            self.compoundFrequencyTF.resignFirstResponder()
        default:
            return
        }
    }
}

extension BankRecurringViewController: BankRecurringViewProtocol {
    func navigate(_ data:BankRecurringModel) {
        DispatchQueue.main.async {
            let recurringSummaryVC = self.storyboard?.instantiateViewController(withIdentifier: "BankRecurringSummaryViewController") as! BankRecurringSummaryViewController
            recurringSummaryVC.recurringModel = data
            self.navigationController?.pushViewController(recurringSummaryVC, animated: true)
        }
    }
    
    func startLoader() {
        ActivityIndicator.start()
    }
    
    func stopLoader() {
        ActivityIndicator.stop()
    }
    
    func showError(error: String) {
        self.view.makeToast(error)
    }
}

