//
//  MegaCashApi.swift
//  Emoney Info
//
//  Created by Wira Irawan on 27/07/24.
//

import Foundation

public class MegaCashApi : UnifiedNfcApi {
    var emoney : Emoney = Emoney()
    var riwayatList: [RiwayatCard] = []
    
    public override init() {}
    
    public func getBalance(resp : Data){
        self.emoney.setCardLabel("MegaCash")
        let value = resp.hexEncodedString()
        self.emoney.setCardNumber(value.subString(from: 4, to: value.count))
        apduRunner.exchangeApdu(apduCommand: EmoneyApduCommands.MEGA_APDU02, completionHandler: {response in
            if (response.sw1 == 0x90 && response.sw2 == 0x00){
                let balance = response.getData().hexEncodedString()
                self.emoney.setBalance(self.getRealBalance(reverseHexa: balance))
                self.emoney.setTampilRiwayat(false)
                self.updateScreen()
                self.apduRunner.sessionEx?.alertMessage = "readFinish".localizeString(string: self.langCode!)
                self.apduRunner.invalidateSession()
            } else {
                self.apduRunner.invalidateSession(msg: "readFailed".localizeString(string: self.langCode!))
            }
        })
    }
    
    func getRealBalance(reverseHexa: String?) -> Int {
        guard let reverseHexa = reverseHexa?.trimmingCharacters(in: .whitespacesAndNewlines), !reverseHexa.isEmpty else {
            return 0
        }
        
        if reverseHexa.count % 2 != 0 {
            return 0
        }
        
        var sb = ""
        for l in stride(from: reverseHexa.count / 2, through: 1, by: -1) {
            let index1 = reverseHexa.index(reverseHexa.startIndex, offsetBy: l * 2 - 2)
            let index2 = reverseHexa.index(reverseHexa.startIndex, offsetBy: l * 2 - 1)
            sb.append(reverseHexa[index1])
            sb.append(reverseHexa[index2])
        }
        return sb.hex2decimal()
    }
    
    private func updateScreen(){
        if (self.apduRunner.callback != nil){
            self.apduRunner.callback?.complete(emoney: self.emoney)
        }
    }
}
