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

import UIKit
import SideMenu
import Toast_Swift

class BondDebenturesViewController: UIViewController {
    
    @IBOutlet var planningDateTF: UITextField!
    @IBOutlet var noOfBondsPurchasedTF: UITextFieldWithDoneButton!
    @IBOutlet var faceValueTF: UITextFieldWithDoneButton!
    @IBOutlet var annualCouponRateTF: UITextFieldWithDoneButton!
    @IBOutlet var termTF: UITextField!
    @IBOutlet var noOfYearsDaysTF: UITextFieldWithDoneButton!
    @IBOutlet var couponPayoutFrequencyTF: UITextField!
    @IBOutlet var investmentDateTF: UITextField!
    @IBOutlet var currentYieldTF: UITextFieldWithDoneButton!
    
    fileprivate let customPicker = ToolbarPickerView()
    var activeTextField = 0
    var menu = Int()
    
    var viewModel = BondDebenturesViewModel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        viewModel.delegate = self
        
        planningDateTF.delegate = self
        noOfBondsPurchasedTF.delegate = self
        faceValueTF.delegate = self
        annualCouponRateTF.delegate = self
        termTF.delegate = self
        noOfYearsDaysTF.delegate = self
        couponPayoutFrequencyTF.delegate = self
        investmentDateTF.delegate = self
        currentYieldTF.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
        }
        let date = Date()
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "dd-MM-yyyy"
        planningDateTF.text = dateFormatter.string(from: date)
        
        //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.termTF.inputView = self.customPicker
        self.termTF.inputAccessoryView = self.customPicker.toolbar
        
        self.couponPayoutFrequencyTF.inputView = self.customPicker
        self.couponPayoutFrequencyTF.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.dateFormat2
            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 noOfBondsPurchasedTF.text?.isEmpty == true {
            self.view.makeToast("Fill number of bonds purchased!")
        } else if faceValueTF.text?.isEmpty == true {
            self.view.makeToast("Fill face value!")
        } else if annualCouponRateTF.text?.isEmpty == true {
            self.view.makeToast("Annual coupon code!")
        } else if termTF.text?.isEmpty == true {
            self.view.makeToast("Select term!")
        } else if noOfYearsDaysTF.text?.isEmpty == true {
            self.view.makeToast("Fill number of years/days!")
        } else if couponPayoutFrequencyTF.text?.isEmpty == true {
            self.view.makeToast("Select coupon payout frequency!")
        } else if investmentDateTF.text?.isEmpty == true {
            self.view.makeToast("Select investment date!")
        } else if currentYieldTF.text?.isEmpty == true {
            self.view.makeToast("Fill current yield!")
        } else {
            if Reachability.isConnectedToNetwork() {
                let yieldInterest = currentYieldTF.text!
                let yieldInterestPercent = Double(yieldInterest)!/100.0
                
                let couponRate = annualCouponRateTF.text!
                let couponRatePercent = Double(couponRate)!/100.0
                viewModel.getBondDebenture(tenureType: termTF.text!, investmentDateString: investmentDateTF.text!, tenure: noOfYearsDaysTF.text!, coupounPayoutFrequency: couponPayoutFrequencyTF.text!, interestCouponRate: String(couponRatePercent), bondFaceValue: faceValueTF.text!, numberOfBondsPurchased: noOfBondsPurchasedTF.text!, currentYield: String(yieldInterestPercent))
            } 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) {
        planningDateTF.text = nil
        noOfBondsPurchasedTF.text = nil
        faceValueTF.text = nil
        annualCouponRateTF.text = nil
        termTF.text = nil
        noOfYearsDaysTF.text = nil
        couponPayoutFrequencyTF.text = nil
        investmentDateTF.text = nil
        currentYieldTF.text = nil
    }
    
}

extension BondDebenturesViewController: 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.FIXED_DEPOSIT_TERM.count
        case 2:
            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.FIXED_DEPOSIT_TERM[row]
        case 2:
            return AppConstant.INTEREST_PAYOUT_FREQUENCY[row]
        default:
            return ""
        }
    }
    
    func pickerView( _ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        
        switch activeTextField{
        case 1:
            termTF.text = AppConstant.FIXED_DEPOSIT_TERM[row]
            break
        case 2:
            couponPayoutFrequencyTF.text = AppConstant.INTEREST_PAYOUT_FREQUENCY[row]
            break
        default:
            break
        }
    }
}

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

extension BondDebenturesViewController: ToolbarPickerViewDelegate {
    func didTapDone() {
        switch activeTextField {
        case 1:
            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 2:
            let row = self.customPicker.selectedRow(inComponent: 0)
            self.customPicker.selectRow(row, inComponent: 0, animated: false)
            self.couponPayoutFrequencyTF.text = AppConstant.INTEREST_PAYOUT_FREQUENCY[row]
            self.couponPayoutFrequencyTF.resignFirstResponder()
        default:
            return
        }
    }
    
    func didTapCancel() {
        switch activeTextField {
        case 1:
            self.termTF.text = nil
            self.termTF.resignFirstResponder()
        case 2:
            self.couponPayoutFrequencyTF.text = nil
            self.couponPayoutFrequencyTF.resignFirstResponder()
        default:
            return
        }
    }
}

extension BondDebenturesViewController: BondDebenturesViewProtocol {
    func navigate(bondModel: BondDebenturesModel, bondOuputListModel: [BondDebenturesOutputListModel]) {
        DispatchQueue.main.async {
            let bondSummaryVC = self.storyboard?.instantiateViewController(withIdentifier: "BondDebenturesSummaryViewController") as! BondDebenturesSummaryViewController
            bondSummaryVC.bondDebentureModel = bondModel
            bondSummaryVC.bondDebentureOutputListModel = bondOuputListModel
            self.navigationController?.pushViewController(bondSummaryVC, animated: true)
        }
    }
    
    func startLoader() {
        ActivityIndicator.start()
    }
    
    func stopLoader() {
        ActivityIndicator.stop()
    }
    
    func showError(error: String) {
        self.view.makeToast(error)
    }
}

