import { IDriver } from "./IDriver";
export class DriverWeb extends IDriver {
    constructor() {
        super();
        // TODO To be set from out side in generic way
        this._recipient = "*";
        /** Stores callback functions by TAN */
        this.callbackList = {};
        if (window.addEventListener) {
            window.addEventListener("message", this.listenerFromHost, false);
        }
        else if (window["attachEvent"]) {
            window["attachEvent"]("onmessage", this.listenerFromHost);
        }
        DriverWeb._instance = this;
    }
    /**
     * Needed for identifying answers to requests sent back from host
     * @result: pseudo-random string
     */
    generateTAN() {
        let tText = "";
        for (let i = 0; i < 5; i++)
            tText += DriverWeb.ALNUMCHARS.charAt(Math.floor(Math.random() * DriverWeb.ALNUMCHARS.length));
        return tText;
    }
    listenerFromHost(evt) {
        const tMD = evt.data;
        const tThis = DriverWeb._instance;
        if (tMD && tMD.transactionCode) {
            if (tThis.callbackList[tMD.transactionCode]) {
                tThis.callbackList[tMD.transactionCode](tMD.data);
                tThis.callbackList[tMD.transactionCode] = undefined;
            }
            else {
                if (tMD.transactionCode === "$PAGEFUNC") {
                    eval(tMD.data);
                }
            }
        }
    }
    sendToHost(cmd, dataObj, callback) {
        const tTAN = this.generateTAN();
        this.callbackList[tTAN] = callback;
        // send the request
        window.parent.window.postMessage({
            cmd: cmd,
            data: dataObj,
            transactionCode: tTAN,
        }, this._recipient);
    }
    detachListeners() {
        if (window.removeEventListener) {
            window.removeEventListener("message", this.listenerFromHost, false);
        }
        else if (window["detachEvent"]) {
            window["detachEvent"]("onmessage", this.listenerFromHost);
        }
    }
}
DriverWeb.ALNUMCHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
