//
//  PublicProvidentViewModel.swift
//  Product Calculator
//
//  Created by Suraj Kumar Mandal on 06/12/21.
//

import Foundation
import Alamofire

class PublicProvidentViewModel {
    
    var delegate: PublicProvidentViewProtocol?
    
    var ppfModel = [PublicProvidentModel]()
    
    //POST PPF Interest API
    func getInterestRate(depositDate:String) {
        if let delegate = delegate {
            delegate.startLoader()
            let url = ApiUrl.BASE_URL + ApiUrl.GET_PPF_INTEREST_RATE
           
            let parameters: [String: String] = [
                "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 interestRate = data["interestRate"] as! Double
                        
                        delegate.setInterestRate(rate: String(interestRate))
                    }
                    
                case .failure(let error):
                    delegate.stopLoader()
                    print(error)
                    //delegate.showError(error: error)
                }
            }
        }
    }
    
    //POST PPF without extension API
    func getPPFOutput(depositAmount:String, tenureType:String, tenure:String, rdDepositFreq:String, compundingFreq:String, depositDate:String) {
        if let delegate = delegate {
            delegate.startLoader()
            let url = ApiUrl.BASE_URL + ApiUrl.GET_PPF_WITHOUT_EXTENSION
            
            var interest = String()
            switch compundingFreq {
            case "Monthly":
                interest = "12"
            case "Bi-Monthly":
                interest = "6"
            case "Quarterly":
                interest = "4"
            case "Triannually":
                interest = "3"
            case "Half Yearly":
                interest = "2"
            case "Annually":
                interest = "1"
            default:
                interest = ""
            }
            
            var depositFrequency = String()
            switch rdDepositFreq {
            case "Monthly":
                depositFrequency = "12"
            case "Bi-Monthly":
                depositFrequency = "6"
            case "Quarterly":
                depositFrequency = "4"
            case "Triannually":
                depositFrequency = "3"
            case "Half Yearly":
                depositFrequency = "2"
            case "Annually":
                depositFrequency = "1"
            default:
                depositFrequency = ""
            }
                        
            let parameters: [String: String] = [
                "deposit": depositAmount,
                "tenureType": tenureType,
                "tenure": tenure,
                "rdDepositFreq": depositFrequency,
                "compundingFreq": interest,
                "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 amountDepositFreq = data["amountDepositFreq"] as! Int
                        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 totalAmountDeposited = data["totalAmountDeposited"] as! Double
                        let maturityAmount = data["maturityAmount"] as! Double
                        let totalInterestReceived = data["totalInterestReceived"] as! Double
                        let maturityDate = data["maturityDate"] as! String
                        let annualAmountDeposited = data["annualAmountDeposited"] as! Double
                        let maturityDisplayDate = data["maturityDisplayDate"] as? String
                        let depositDisplayDate = data["depositDisplayDate"] as? String
                        let currentBalance = data["currentBalance"] as! Double
                        
                        let ppfFixedAmountLookupList = data["ppfFixedAmountLookupList"] as! [NSDictionary]
                        
                        let ppfData = PublicProvidentModel(depositDate: depositDate ?? "", maturityDate: maturityDate, maturityDisplayDate: maturityDisplayDate ?? "", depositDisplayDate: depositDisplayDate ?? "", amountDepositFreq: amountDepositFreq, term: term, depositAmount: depositAmount, annualInterest: annualInterest, compundFreq: compundFreq, totalAmountDeposited: totalAmountDeposited, maturityAmount: maturityAmount, totalInterestReceived: totalInterestReceived, annualAmountDeposited: annualAmountDeposited, currentBalance: currentBalance)
                        
                        for list in ppfFixedAmountLookupList {
                            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 interestEarned = list.value(forKey: "interestEarned") as! Double
                            let interestCredited = list.value(forKey: "interestCredited") as! Double
                            let interestRate = list.value(forKey: "interestRate") as! Double
                            let totalInterestAccrued = list.value(forKey: "totalInterestAccrued") as! Double
                            let closingBalance = list.value(forKey: "closingBalance") as! Double
                            let daysToMaturity = list.value(forKey: "daysToMaturity") as! NSNumber
                            let currentBalance = list.value(forKey: "currentBalance") as! Double
                                                        
                            let list = PPFLookupList(serialNo: Int(truncating: serialNo), daysToMaturity: Int(truncating: daysToMaturity), referenceDate: referenceDate, referenceMonth: referenceMonth, financialYear: financialYear, openingBal: openingBal, amountDeposited: amountDeposited, interestEarned: interestEarned, interestCredited: interestCredited, totalInterestAccrued: totalInterestAccrued, closingBalance: closingBalance, interestRate: interestRate, currentBalance:currentBalance)
                            
                            ppfData.ppfFixedAmountLookupList.append(list)
                        }
                        self.ppfModel.append(ppfData)
                        delegate.navigate(ppfData)
                    }
                    
                case .failure(let error):
                    delegate.stopLoader()
                    print(error)
                    //delegate.showError(error: error)
                }
            }
        }
    }
    
    //POST PPF with extension API
    func getPPFExtOutput(depositAmount:String, tenureType:String, tenure:String, rdDepositFreq:String, compundingFreq:String, depositDate:String,   totalAmountDiposited:String) {
        if let delegate = delegate {
            delegate.startLoader()
            let url = ApiUrl.BASE_URL + ApiUrl.GET_PPF_WITH_EXTENSION
            
            var interest = String()
            switch compundingFreq {
            case "Monthly":
                interest = "12"
            case "Bi-Monthly":
                interest = "6"
            case "Quarterly":
                interest = "4"
            case "Triannually":
                interest = "3"
            case "Half Yearly":
                interest = "2"
            case "Annually":
                interest = "1"
            default:
                interest = ""
            }
            
            var depositFrequency = String()
            switch rdDepositFreq {
            case "Monthly":
                depositFrequency = "12"
            case "Bi-Monthly":
                depositFrequency = "6"
            case "Quarterly":
                depositFrequency = "4"
            case "Triannually":
                depositFrequency = "3"
            case "Half Yearly":
                depositFrequency = "2"
            case "Annually":
                depositFrequency = "1"
            default:
                depositFrequency = ""
            }
                        
            let parameters: [String: String] = [
                "deposit": depositAmount,
                "tenureType": tenureType,
                "tenure": tenure,
                "rdDepositFreq": depositFrequency,
                "compundingFreq": interest,
                "depositDate": depositDate,
                //"maturityAmount": maturityAmount,
                "totalAmountDiposited": totalAmountDiposited
            ]
            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 amountDepositFreq = data["amountDepositFreq"] as! Int
                        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 totalAmountDeposited = data["totalAmountDeposited"] as! Double
                        let maturityAmount = data["maturityAmount"] as! Double
                        let totalInterestReceived = data["totalInterestReceived"] as! Double
                        let maturityDate = data["depositMaturityDate"] as! String
                        let annualAmountDeposited = data["annualAmountDeposited"] as! Double
                        let maturityDisplayDate = data["maturityDisplayDate"] as! String
                        let depositDisplayDate = data["depositDisplayDate"] as! String
                        let currentBalance = data["currentBalance"] as! Double
                        
                        let ppfFixedAmountLookupList = data["ppfFixedAmountLookupList"] as! [NSDictionary]
                        
                        let ppfData = PublicProvidentModel(depositDate: depositDate ?? "", maturityDate: maturityDate, maturityDisplayDate: maturityDisplayDate, depositDisplayDate: depositDisplayDate, amountDepositFreq: amountDepositFreq, term: term, depositAmount: depositAmount, annualInterest: annualInterest, compundFreq: compundFreq, totalAmountDeposited: totalAmountDeposited, maturityAmount: maturityAmount, totalInterestReceived: totalInterestReceived, annualAmountDeposited: annualAmountDeposited, currentBalance: currentBalance)
                        
                        for list in ppfFixedAmountLookupList {
                            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 interestEarned = list.value(forKey: "interestEarned") as! Double
                            let interestCredited = list.value(forKey: "interestCredited") as! Double
                            let interestRate = list.value(forKey: "interestRate") as! Double
                            let totalInterestAccrued = list.value(forKey: "totalInterestAccrued") as! Double
                            let closingBalance = list.value(forKey: "closingBalance") as! Double
                            let daysToMaturity = list.value(forKey: "daysToMaturity") as! NSNumber
                            let currentBalance = list.value(forKey: "currentBalance") as! Double
                                                        
                            let list = PPFLookupList(serialNo: Int(truncating: serialNo), daysToMaturity: Int(truncating: daysToMaturity), referenceDate: referenceDate, referenceMonth: referenceMonth, financialYear: financialYear, openingBal: openingBal, amountDeposited: amountDeposited, interestEarned: interestEarned, interestCredited: interestCredited, totalInterestAccrued: totalInterestAccrued, closingBalance: closingBalance, interestRate: interestRate, currentBalance:currentBalance)
                            
                            ppfData.ppfFixedAmountLookupList.append(list)
                        }
                        self.ppfModel.append(ppfData)
                        delegate.navigate(ppfData)
                    }
                    
                case .failure(let error):
                    delegate.stopLoader()
                    print(error)
                    //delegate.showError(error: error)
                }
            }
        }
    }
    
}

protocol PublicProvidentViewProtocol {
    func startLoader()
    func stopLoader()
    func showError(error:String)
    func setInterestRate(rate:String)
    func navigate(_ data:PublicProvidentModel)
}
