//
//  BondDebenturesViewModel.swift
//  Product Calculator
//
//  Created by Suraj Kumar Mandal on 30/11/21.
//

import Foundation
import Alamofire

class BondDebenturesViewModel {
    
    var delegate: BondDebenturesViewProtocol?
    
    var bondDebentureModel = [BondDebenturesModel]()
    var bondDebentureOutputListModel = [BondDebenturesOutputListModel]()
    
    //POST Bond Debenture API
    func getBondDebenture(tenureType:String, investmentDateString:String, tenure:String, coupounPayoutFrequency:String, interestCouponRate:String, bondFaceValue:String, numberOfBondsPurchased:String, currentYield:String) {
        if let delegate = delegate {
            delegate.startLoader()
            let url = ApiUrl.BASE_URL + ApiUrl.GET_BOND_DEBENTURE
            
            var terms = String()
            switch tenureType {
            case "Year":
                terms = "Y"
            case "Days":
                terms = "D"
            default:
                terms = ""
            }
            
            var payoutFrequency = String()
            switch coupounPayoutFrequency {
            case "Monthly":
                payoutFrequency = "12"
            case "Bi-Monthly":
                payoutFrequency = "6"
            case "Quarterly":
                payoutFrequency = "4"
            case "Triannually":
                payoutFrequency = "3"
            case "Half Yearly":
                payoutFrequency = "2"
            case "Annually":
                payoutFrequency = "1"
            default:
                payoutFrequency = ""
            }
                        
            let parameters: [String: String] = [
                "tenureType": terms,
                "investmentDate": investmentDateString,
                "tenure": tenure,
                "coupounPayoutFrequency": payoutFrequency,
                "interestCouponRate": interestCouponRate,
                "bondFaceValue": bondFaceValue,
                "numberOfBondsPurchased": numberOfBondsPurchased,
                "currentYield": currentYield
            ]
            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 serialNo = data["serialNo"] as! Int
                        let referenceDate = data["referenceDate"] as? String
                        let referenceMonth = data["referenceMonth"] as? String
                        let financialYear = data["financialYear"] as? String
                        let amountDeposited = data["amountDeposited"] as! Double
                        let couponReceived = data["couponReceived"] as! Double
                        let totalCouponReceived = data["totalCouponReceived"] as! Double
                        let daysToMaturity = data["daysToMaturity"] as! String
                        let viewMaturityDate = data["viewMaturityDate"] as? String
                        let numberOfBondsPurchased = data["numberOfBondsPurchased"] as! Int
                        let bondFaceValue = data["bondFaceValue"] as! Double
                        let effectiveTimeToMaturity = data["effectiveTimeToMaturity"] as! Double
                        let interestCouponRate = data["interestCouponRate"] as! Double
                        let term = data["term"] as? Int
                        let coupounPayoutFrequency = data["coupounPayoutFrequency"] as! Int
                        let investmentDate = data["investmentDate"] as? String
                        let currentYield = data["currentYield"] as! Double
                        let currentValue = data["currentValue"] as! Double
                        let tenureYearsDays = data["tenureYearsDays"] as? Int
                        let totalMonths = data["totalMonths"] as! Int
                                                
                        let bondData = BondDebenturesModel(serialNo: serialNo, numberOfBondsPurchased: numberOfBondsPurchased, term: term ?? 0, coupounPayoutFrequency: coupounPayoutFrequency, tenureYearsDays: tenureYearsDays ?? 0, totalMonths: totalMonths, referenceDate: referenceDate ?? "", referenceMonth: referenceMonth ?? "", financialYear: financialYear ?? "", daysToMaturity: daysToMaturity, viewMaturityDate: viewMaturityDate ?? "", investmentDate: investmentDate ?? "", amountDeposited: amountDeposited, couponReceived: couponReceived, totalCouponReceived: totalCouponReceived, bondFaceValue: bondFaceValue, effectiveTimeToMaturity: effectiveTimeToMaturity, interestCouponRate: interestCouponRate, currentYield: currentYield, currentValue: currentValue)

                        self.bondDebentureModel.append(bondData)
                        let dateString = daysToMaturity.stringBefore("T")
                        self.getBondDebentureOutputList(numberOfBonds: String(numberOfBondsPurchased), bondFaceValue: String(bondFaceValue), coupounPayoutFrequency: payoutFrequency, investmentDate: investmentDateString, dtMaturityDate: self.convertDateFormat(inputDate: dateString), couponReceivedValue: String(couponReceived), totalMonths: String(totalMonths), bondModel: bondData)
                    }
                    
                case .failure(let error):
                    delegate.stopLoader()
                    print(error)
                    //delegate.showError(error: error)
                }
            }
        }
    }
    
    //POST Bond Debenture Output List
    func getBondDebentureOutputList(numberOfBonds:String, bondFaceValue:String, coupounPayoutFrequency:String, investmentDate:String, dtMaturityDate:String, couponReceivedValue:String, totalMonths:String, bondModel:BondDebenturesModel) {
        if let delegate = delegate {
            delegate.startLoader()
            let url = ApiUrl.BASE_URL + ApiUrl.GET_BOND_DEBENTURE_OUTPUT_LIST
                        
            let parameters: [String: String] = [
                "numberOfBonds": numberOfBonds,
                "bondFaceValue": bondFaceValue,
                "coupounPayoutFrequency": coupounPayoutFrequency,
                "investmentDate": investmentDate,
                "dtMaturityDate": dtMaturityDate,
                "couponReceivedValue": couponReceivedValue,
                "totalMonths": totalMonths
            ]
            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 {
                        for item in data {
                            let serialNo = item["serialNo"] as! Int
                            let referenceDate = item["referenceDate"] as! String
                            let referenceMonth = item["referenceMonth"] as! String
                            let financialYear = item["financialYear"] as! String
                            let bondAmountDeposited = item["bondAmountDeposited"] as! Double
                            let couponReceived = item["couponReceived"] as! Double
                            let totalCouponReceived = item["totalCouponReceived"] as! Double
                            let daysToMaturity = item["daysToMaturity"] as! Int
                            
                            let outputList = BondDebenturesOutputListModel(serialNo: serialNo, daysToMaturity: daysToMaturity, referenceDate: referenceDate, referenceMonth: referenceMonth, financialYear: financialYear, bondAmountDeposited: bondAmountDeposited, couponReceived: couponReceived, totalCouponReceived: totalCouponReceived)
                            self.bondDebentureOutputListModel.append(outputList)
                        }
                    }
                    delegate.navigate(bondModel: bondModel, bondOuputListModel: self.bondDebentureOutputListModel)
                    
                case .failure(let error):
                    delegate.stopLoader()
                    print(error)
                    //delegate.showError(error: error)
                }
            }
        }
    }
    
    func convertDateFormat(inputDate: String) -> String {
        let olDateFormatter = DateFormatter()
        olDateFormatter.dateFormat = "yyyy-MM-dd"
        let oldDate = olDateFormatter.date(from: inputDate)
        let convertDateFormatter = DateFormatter()
        convertDateFormatter.dateFormat = "dd/MM/yyyy"
        return convertDateFormatter.string(from: oldDate!)
    }
    
}

protocol BondDebenturesViewProtocol {
    func startLoader()
    func stopLoader()
    func showError(error:String)
    func navigate(bondModel:BondDebenturesModel, bondOuputListModel:[BondDebenturesOutputListModel])
}
