const { errorCode } = require("../constant");
const KHQRTag = require("../constant/KHQRTag");
const { KHQRResponse } = require("../model");
const cutString = require("./cutString");

function getQRContent(KHQRString) {
    if (KHQRString.length < 8) {
        return KHQRResponse(errorCode.KHQR_INVALID, { error: true });
    }
    let decodeElement = {};
    let khqr = KHQRString;
    for (let i = 0; i < KHQRTag.length; i++) {
        let element = cutString(khqr);
        const data = KHQRTag[i];
        let khqrInstance;
        if (element.tag == data.tag) {
            khqrInstance = new data.instance(element.tag, element.value);
            khqr = element.slicedString;
            if (element.tag == "62") {
                decodeElement["billNumber"] = khqrInstance.billNumber;
                decodeElement["storeLabel"] = khqrInstance.storeLabel;
                decodeElement["terminalLabel"] = khqrInstance.terminalLabel;
            }
        } else if (element.tag == "30") {
            khqrInstance = new data.instance(element.tag, element.value);
            khqr = element.slicedString;
        } else {
            if (data.tag == "62") {
                khqrInstance = new data.instance(element.tag, "");
                decodeElement["billNumber"] = khqrInstance.billNumber;
                decodeElement["storeLabel"] = khqrInstance.storeLabel;
                decodeElement["terminalLabel"] = khqrInstance.terminalLabel;
            }
            if (data.type == "merchantAccount")
                khqrInstance = new data.instance("", "");
            else khqrInstance = new data.instance(element.tag, "");
        }
        decodeElement[data.type] = khqrInstance;
    }

    return decodeElement;
}

module.exports = getQRContent;
