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

import UIKit

class NonEMISummaryViewController: UIViewController {
    
    @IBOutlet var interestPaidHalfYearlyTF: UITextField!
    @IBOutlet var overallInterestReceivedTF: UITextField!
    @IBOutlet var loanEndDateTF: UITextField!
    @IBOutlet var viewDetailedButton: UIButton!
    @IBOutlet var collectionView: UICollectionView!
    
    var viewModel = NonEMISummaryViewModel()
    
    var nonEmiModel:EMILoanOriginalModel?
    var nonEmiOutputList = [EMIOriginalLookupList]()
        
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        setupUI()
        setupData()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        viewModel.delegate = self
        let date = nonEmiModel!.loanStartDate
        let startDate = date?.stringBefore("T") ?? ""
        let date1 = nonEmiModel!.loanEndDate
        let endDate = date1?.stringBefore("T") ?? ""
        viewModel.getNonEMIOutputList(begningBal: String(nonEmiModel!.loanAmount!), interestFrequency: String(nonEmiModel!.interestPaymentFrequency!), refDate: startDate, loanEndDate: endDate, interestPaidAmount: String(nonEmiModel!.totalInterestPaid!), totalMonths: String(nonEmiModel!.loanTenure!))
    }
    
    func setupUI() {
        viewDetailedButton.isHidden = false
        collectionView.isHidden = true
    }
    
    func setupData() {
        interestPaidHalfYearlyTF.text = ""
        overallInterestReceivedTF.text = String(format: "%.2f", "\(nonEmiModel!.totalInterestPaid!)")
        let date = nonEmiModel!.loanEndDate
        let endDate = date?.stringBefore("T")
        loanEndDateTF.text = endDate
        print(String(format: "%.2f", "\(nonEmiModel!.totalInterestPaid!)"))
        print(endDate)
    }
    
    
    /*
     // 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
        collectionView.isHidden = false
    }
    
}

extension NonEMISummaryViewController : NonEMISummaryViewProtocol {
    func loadData(_ data: [EMIOriginalLookupList]) {
        self.nonEmiOutputList = data
        self.collectionView.reloadData()
    }
    
    func startLoader() {
        ActivityIndicator.start()
    }
    
    func stopLoader() {
        ActivityIndicator.stop()
    }
    
    func showError(error: String) {
        self.view.makeToast(error)
    }
}

extension NonEMISummaryViewController : UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return nonEmiOutputList.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "NonEMITableViewCell", for: indexPath) as? NonEMITableViewCell
        
        cell?.monthLabel.text = nonEmiOutputList[indexPath.row].referenceMonth
        cell?.beginningLoanBalanceLabel.text = String(format: "%.2f", "\(nonEmiOutputList[indexPath.row].begningBal!)")
        cell?.principalPaidLabel.text = String(format: "%.2f", "\(nonEmiOutputList[indexPath.row].principalPayment!)")
        cell?.interestPaidLabel.text = String(format: "%.2f", "\(nonEmiOutputList[indexPath.row].interestPayment!)")
        cell?.closingLoanBalanceLabel.text = String(format: "%.2f", "\(nonEmiOutputList[indexPath.row].endingBalance!)")
        cell?.totalPrincipalPaidLabel.text = String(format: "%.2f", "\(nonEmiOutputList[indexPath.row].totalPrincipalPaid!)")
        cell?.totalInterestPaidLabel.text = String(format: "%.2f", "\(nonEmiOutputList[indexPath.row].totalInterestPaid!)")
        
        return cell!
    }
}

// MARK: - UICollectionViewDataSource
extension NonEMISummaryViewController: UICollectionViewDataSource {
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return nonEmiOutputList.count
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 7
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        // swiftlint:disable force_cast
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "NonEMICollectionViewCell", for: indexPath) as! NonEMICollectionViewCell
        
        if indexPath.section % 2 != 0 {
            cell.backgroundColor = UIColor(white: 242/255.0, alpha: 1.0)
        } else {
            cell.backgroundColor = UIColor.white
        }
        
        if indexPath.section == 0 {
            if indexPath.row == 0 {
                cell.contentLabel.text = "Month"
            } else if indexPath.row == 1 {
                cell.contentLabel.text = "Beginning Loan Balance"
            } else if indexPath.row == 2 {
                cell.contentLabel.text = "Principal Paid"
            } else if indexPath.row == 3 {
                cell.contentLabel.text = "Interest Paid"
            } else if indexPath.row == 4 {
                cell.contentLabel.text = "Closing Loan Balance"
            } else if indexPath.row == 5 {
                cell.contentLabel.text = "Total Principal Paid to Date"
            } else if indexPath.row == 6 {
                cell.contentLabel.text = "Total Interest Paid to Date"
            }
        } else {
            if indexPath.row == 0 {
                cell.contentLabel.text = nonEmiOutputList[indexPath.row].referenceMonth
            } else if indexPath.row == 1 {
                cell.contentLabel.text = String(format: "%.2f", "\(nonEmiOutputList[indexPath.row].begningBal!)")
            } else if indexPath.row == 2 {
                cell.contentLabel.text = String(format: "%.2f", "\(nonEmiOutputList[indexPath.row].principalPayment!)")
            } else if indexPath.row == 3 {
                cell.contentLabel.text = String(format: "%.2f", "\(nonEmiOutputList[indexPath.row].interestPayment!)")
            } else if indexPath.row == 4 {
                cell.contentLabel.text = String(format: "%.2f", "\(nonEmiOutputList[indexPath.row].endingBalance!)")
            } else if indexPath.row == 5 {
                cell.contentLabel.text = String(format: "%.2f", "\(nonEmiOutputList[indexPath.row].totalPrincipalPaid!)")
            } else if indexPath.row == 6 {
                cell.contentLabel.text = String(format: "%.2f", "\(nonEmiOutputList[indexPath.row].totalInterestPaid!)")
            }
        }
        
        return cell
    }
    
}

// MARK: - UICollectionViewDelegate
extension NonEMISummaryViewController: UICollectionViewDelegate {
    
}
