//
//  EMILoanSummaryViewController.swift
//  Product Calculator
//
//  Created by Suraj Kumar Mandal on 07/12/21.
//

import UIKit
import Toast_Swift

class EMILoanSummaryViewController: UIViewController {

    @IBOutlet var label1: UILabel!
    @IBOutlet var textField1: UITextField!
    @IBOutlet var label2: UILabel!
    @IBOutlet var textField2: UITextField!
    @IBOutlet var label3: UILabel!
    @IBOutlet var textField3: UITextField!
    @IBOutlet var viewDetailedButton: UIButton!
    @IBOutlet var tableView: UITableView!
    
    var viewModel = EMILoanSummaryViewModel()
    
    var emiOriginalModel:EMILoanOriginalModel?
    var emiOutstandingModel:EMILoanOutstandingModel?
    var emiOriginalOutputList = [EMIOriginalLookupList]()
    var emiOutstandingOutputList = [EMIOutstandingLookupList]()
    
    var loanType = String()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        setupUI()
        setupData()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        viewModel.delegate = self
        if loanType == "Original Loan Amount(Rs)" {
            viewModel.getEMIOriginalOutputList(numberOfEMI: String(emiOriginalModel!.numberOfEMI ?? 0), loanStartingDate: String(emiOriginalModel?.loanStartDate ?? ""), originalLoanAmount: String(emiOriginalModel?.loanAmount ?? 0), loanEMIAmt: String(emiOriginalModel?.emiAmount ?? 0), originalInterestRate: String(emiOriginalModel?.interestRate ?? 0), loanFlag: String(emiOriginalModel?.loan_original_flag ?? ""))
        } else {
            viewModel.getEMIOutstandingOutputList(numberOfEMI: String(emiOutstandingModel!.numberOfEMI ?? 0), loanStartingDate: String(emiOutstandingModel?.loanStartDate ?? ""), originalLoanAmount: String(emiOutstandingModel?.loanAmount ?? 0), loanEMIAmt: String(emiOutstandingModel?.emiAmount ?? 0), originalInterestRate: String(emiOutstandingModel?.interestRate ?? 0), loanFlag: String(emiOutstandingModel?.loan_original_flag ?? ""))
        }
    }
    
    func setupUI() {
        viewDetailedButton.isHidden = false
        tableView.isHidden = true
    }
    
    func setupData() {
        if loanType == "Original Loan Amount(Rs)" {
            label1.isHidden = false
            label2.isHidden = false
            label3.isHidden = false
            textField1.isHidden = false
            textField2.isHidden = false
            textField3.isHidden = false
            //Head label name
            label1.text = "No. of Original EMI Installments"
            label2.text = "Original EMI Amount(Rs)"
            label3.text = "Original Loan End Date"
            textField1.text = String(emiOriginalModel!.numberOfEMI!)
            textField2.text = String(format: "%.2f", "\(emiOriginalModel!.emiAmount!)")
            let date = emiOriginalModel!.loanEndDate
            let dateString = date?.stringBefore("T")
            textField3.text = convertDateFormat(inputDate: dateString!)
        } else {
            textField1.isHidden = false
            textField2.isHidden = false
            textField3.isHidden = true
            label1.isHidden = false
            label2.isHidden = false
            label3.isHidden = true
            //Head label name
            label1.text = "No. of Pending Installments"
            label2.text = "Current Loan End Date"
            textField1.text = String(emiOutstandingModel!.numberOfEMI!)
            let date = emiOriginalModel!.loanEndDate
            let dateString = date?.stringBefore("T")
            textField2.text = convertDateFormat(inputDate: dateString!)
        }
    }
    
    
    /*
     // 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 viewDetailedProjectionAction(_ sender: Any) {
        viewDetailedButton.isHidden = true
        tableView.isHidden = false
    }
    
}

extension EMILoanSummaryViewController : EMILoanSummaryViewProtocol {
    func startLoader() {
        ActivityIndicator.start()
    }
    
    func stopLoader() {
        ActivityIndicator.stop()
    }
    
    func showError(error: String) {
        self.view.makeToast(error)
    }
    
    func loadOriginal(_ data: [EMIOriginalLookupList]) {
        self.emiOriginalOutputList = data
        self.tableView.reloadData()
    }
    
    func loadOutstanding(_ data: [EMIOutstandingLookupList]) {
        self.emiOutstandingOutputList = data
        self.tableView.reloadData()
    }
}

extension EMILoanSummaryViewController : UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if loanType == "Original Loan Amount(Rs)" {
            return emiOriginalOutputList.count
        } else {
            return emiOutstandingOutputList.count
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "EMILoanTableViewCell", for: indexPath) as? EMILoanTableViewCell
        
        if loanType == "Original Loan Amount(Rs)" {
            cell?.monthLabel.text = emiOriginalOutputList[indexPath.row].referenceMonth
            cell?.installmentNoLabel.text = String(format: "%.2f", "\(emiOriginalOutputList[indexPath.row].installmentNumber!)")
            cell?.beginningBalanceLabel.text = String(format: "%.2f", "\(emiOriginalOutputList[indexPath.row].begningBal!)")
            cell?.interestPaymentLabel.text = String(format: "%.2f", "\(emiOriginalOutputList[indexPath.row].interestPayment!)")
            cell?.principalPaymentLabel.text = String(format: "%.2f", "\(emiOriginalOutputList[indexPath.row].principalPayment!)")
            cell?.endingBalanceLabel.text = String(format: "%.2f", "\(emiOriginalOutputList[indexPath.row].endingBalance!)")
            cell?.emiAmountLabel.text = String(format: "%.2f", "\(emiOriginalOutputList[indexPath.row].emiAmount!)")
            cell?.totalPrincipalPaidToDateLabel.text = String(format: "%.2f", "\(emiOriginalOutputList[indexPath.row].totalPrincipalPaid!)")
            cell?.totalInterestPaidToDateLabel.text = String(format: "%.2f", "\(emiOriginalOutputList[indexPath.row].totalInterestPaid!)")
        } else {
            cell?.monthLabel.text = emiOutstandingOutputList[indexPath.row].referenceMonth
            cell?.installmentNoLabel.text = String(format: "%.2f", "\(emiOutstandingOutputList[indexPath.row].installmentNumber!)")
            cell?.beginningBalanceLabel.text = String(format: "%.2f", "\(emiOutstandingOutputList[indexPath.row].begningBal!)")
            cell?.interestPaymentLabel.text = String(format: "%.2f", "\(emiOutstandingOutputList[indexPath.row].interestPayment!)")
            cell?.principalPaymentLabel.text = String(format: "%.2f", "\(emiOutstandingOutputList[indexPath.row].principalPayment!)")
            cell?.endingBalanceLabel.text = String(format: "%.2f", "\(emiOutstandingOutputList[indexPath.row].endingBalance!)")
            cell?.emiAmountLabel.text = String(format: "%.2f", "\(emiOutstandingOutputList[indexPath.row].emiAmount!)")
            cell?.totalPrincipalPaidToDateLabel.text = String(format: "%.2f", "\(emiOutstandingOutputList[indexPath.row].totalPrincipalPaid!)")
            cell?.totalInterestPaidToDateLabel.text = String(format: "%.2f", "\(emiOutstandingOutputList[indexPath.row].totalInterestPaid!)")
        }
        
        return cell!
    }
}
