//
//  FixedDepositViewModel.swift
//  Product Calculator
//
//  Created by Suraj Kumar Mandal on 16/11/21.
//

import Foundation
import Alamofire

class FixedDepositViewModel {
    
    var delegate: FixedDepositViewProtocol?
    
    var fdtdrDetails = [FDTDRDetailsModel]()
    var fdStdrDetails = [FDSTDRDetailsModel]()
    
    //Fixed deposit TDR API call
    func getBankFDTDRDetails(depositAmount:String, annualInterest:String, termYearsDays:String, tenure:String, payoutFrq:String, depositDate:String) {
        if let delegate = delegate {
            delegate.startLoader()
            let url = ApiUrl.BASE_URL + ApiUrl.GET_FDTDR
            
            var terms = String()
            switch termYearsDays {
            case "Year":
                terms = "Y"
            case "Days":
                terms = "D"
            default:
                terms = ""
            }
            
            var interestPayoutFrequency = String()
            switch payoutFrq {
            case "Monthly":
                interestPayoutFrequency = "12"
            case "Bi-Monthly":
                interestPayoutFrequency = "6"
            case "Quarterly":
                interestPayoutFrequency = "4"
            case "Triannually":
                interestPayoutFrequency = "3"
            case "Half Yearly":
                interestPayoutFrequency = "2"
            case "Annually":
                interestPayoutFrequency = "1"
            default:
                interestPayoutFrequency = ""
            }
            
            let parameters: [String: String] = [
                "depositAmount": depositAmount,
                "annualInterest": annualInterest,
                "termYearsDays": terms,
                "tenure": tenure,
                "payoutFrq": interestPayoutFrequency,
                "depositDate": depositDate
            ]
            print(parameters)
            
            AF.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default).responseJSON { response in
                
                switch response.result {
                case .success(let value):
                    delegate.stopLoader()
                    print(value)
                    let data = value as! NSDictionary
                    print(data)
                    DispatchQueue.main.async {
                        let interestReceived = data["interestReceived"] as? Double
                        let totalInterestReceived = data["totalInterestReceived"] as? Double
                        let maturityDate = data["maturityDate"] as? String
                        let maturityDisplayDate = data["maturityDisplayDate"] as? String
                        let bankFdTdrLookupList = data["bankFdTdrLookupList"] as! [NSDictionary]
                        
                        let fdtdrData = FDTDRDetailsModel(maturityDate: maturityDate ?? "", maturityDisplayDate: maturityDisplayDate ?? "", interestReceived: Int(interestReceived ?? 0), totalInterestReceived: Int(totalInterestReceived ?? 0))
                        
                        for list in bankFdTdrLookupList {
                            let serialNo = list.value(forKey: "serialNo") as! NSNumber
                            let referenceDate = list.value(forKey: "referenceDate") as! String
                            let referenceMonth = list.value(forKey: "referenceMonth") as! String
                            let financialYear = list.value(forKey: "financialYear") as! String
                            let amountDeposited = list.value(forKey: "amountDeposited") as! Double
                            let interestReceived = list.value(forKey: "interestReceived") as! Double
                            let interestAccrued = list.value(forKey: "interestAccrued") as! Double
                            let totalInterestAccrued = list.value(forKey: "totalInterestAccrued") as! Double
                            let daysToMaturity = list.value(forKey: "daysToMaturity") as! NSNumber
                                                        
                            let list = FDTDRLookupList(serialNo: Int(truncating: serialNo), amountDeposited: Int(amountDeposited), interestReceived: Int(interestReceived), interestAccrued: Int(interestAccrued), totalInterestAccrued: Int(totalInterestAccrued), daysToMaturity: Int(truncating: daysToMaturity), referenceDate: referenceDate, referenceMonth: referenceMonth, financialYear: financialYear)
                            
                            fdtdrData.bankFdTdrLookupList.append(list)
                        }
                        self.fdtdrDetails.append(fdtdrData)
                        delegate.navigateWithFDTDR(fdtdrData)
                    }
                    
                case .failure(let error):
                    delegate.stopLoader()
                    print(error)
                    //delegate.showError(error: error)
                }
            }
        }
    }
    
    //Fixed deposit STDR API call
    func getBankFDSTDRCDCPOutputList(depositAmount:String, annualInterest:String, termYearsDays:String, tenure:String, compoundFrequency:String, depositDate:String) {
        if let delegate = delegate {
            delegate.startLoader()
            let url = ApiUrl.BASE_URL + ApiUrl.GET_FDSTDR
            
            var terms = String()
            switch termYearsDays {
            case "Year":
                terms = "Y"
            case "Days":
                terms = "D"
            default:
                terms = ""
            }
            
            var interestPayoutFrequency = String()
            switch compoundFrequency {
            case "Monthly":
                interestPayoutFrequency = "12"
            case "Bi-Monthly":
                interestPayoutFrequency = "6"
            case "Quarterly":
                interestPayoutFrequency = "4"
            case "Triannually":
                interestPayoutFrequency = "3"
            case "Half Yearly":
                interestPayoutFrequency = "2"
            case "Annually":
                interestPayoutFrequency = "1"
            default:
                interestPayoutFrequency = ""
            }
            
            let parameters: [String: String] = [
                "depositAmount": depositAmount,
                "annualInterest": annualInterest,
                "termYearsDays": terms,
                "tenure": tenure,
                "compoundFrequency": interestPayoutFrequency,
                "depositDate": depositDate
            ]
            print(parameters)
            
            AF.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default).responseJSON { response in
                
                switch response.result {
                case .success(let value):
                    delegate.stopLoader()
                    print(value)
                    let data = value as! NSDictionary
                    print(data)
                    DispatchQueue.main.async {
                        let depositAmount = data["depositAmount"] as! Double
                        let annualInterest = data["annualInterest"] as! Double
                        let term = data["term"] as! Int
                        let compundFreq = data["compundFreq"] as! Double
                        let depositDate = data["depositDate"] as! String
                        let maturityAmount = data["maturityAmount"] as! Double
                        let interestReceived = data["interestReceived"] as! Double
                        let totalInterestReceived = data["totalInterestReceived"] as! Double
                        let maturityDate = data["maturityDate"] as! String
                        
                        let bankFdStdrLookupList = data["bankFdTdrLookupList"] as! [NSDictionary]
                        
                        let fdStdrData = FDSTDRDetailsModel(depositDate: depositDate, maturityDate: maturityDate, term: term, depositAmount: depositAmount, annualInterest: annualInterest, compundFreq: compundFreq, maturityAmount: maturityAmount, interestReceived: interestReceived, totalInterestReceived: totalInterestReceived)
                        
                        for list in bankFdStdrLookupList {
                            let serialNo = list.value(forKey: "serialNo") as! NSNumber
                            let referenceDate = list.value(forKey: "referenceDate") as! String
                            let referenceMonth = list.value(forKey: "referenceMonth") as! String
                            let financialYear = list.value(forKey: "financialYear") as! String
                            let openingBal = list.value(forKey: "openingBal") as! Double
                            let amountDeposited = list.value(forKey: "amountDeposited") as! Double
                            let interestCredited = list.value(forKey: "interestCredited") as! Double
                            let interestAccrued = list.value(forKey: "interestAccrued") as! Double
                            let totalInterestReceived = list.value(forKey: "totalInterestReceived") as! Double
                            let closingBalance = list.value(forKey: "closingBalance") as! Double
                            let daysToMaturity = list.value(forKey: "daysToMaturity") as! NSNumber
                                                        
                            let list = FDSTDRLookupList(serialNo: Int(truncating: serialNo), openingBal: openingBal, amountDeposited: amountDeposited, interestAccrued: interestAccrued, totalInterestReceived: totalInterestReceived, interestCredited: interestCredited, daysToMaturity: Int(truncating: daysToMaturity), referenceDate: referenceDate, referenceMonth: referenceMonth, financialYear: financialYear, closingBalance: closingBalance)
                            
                            fdStdrData.bankFdStdrLookupList.append(list)
                        }
                        self.fdStdrDetails.append(fdStdrData)
                        delegate.navigateWithFDSTDR(fdStdrData)
                    }
                    
                case .failure(let error):
                    delegate.stopLoader()
                    print(error)
                    //delegate.showError(error: error)
                }
            }
        }
    }
    
}

protocol FixedDepositViewProtocol {
    func startLoader()
    func stopLoader()
    func showError(error:String)
    func navigateWithFDTDR(_ data:FDTDRDetailsModel)
    func navigateWithFDSTDR(_ data:FDSTDRDetailsModel)
}
