"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var IDriver_1 = require("./IDriver");
var DriverWeb = /** @class */ (function (_super) {
    tslib_1.__extends(DriverWeb, _super);
    function DriverWeb() {
        var _this = _super.call(this) || this;
        // 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;
        return _this;
    }
    /**
     * Needed for identifying answers to requests sent back from host
     * @result: pseudo-random string
     */
    DriverWeb.prototype.generateTAN = function () {
        var tText = "";
        for (var i = 0; i < 5; i++)
            tText += DriverWeb.ALNUMCHARS.charAt(Math.floor(Math.random() * DriverWeb.ALNUMCHARS.length));
        return tText;
    };
    DriverWeb.prototype.listenerFromHost = function (evt) {
        var tMD = evt.data;
        var 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);
                }
            }
        }
    };
    DriverWeb.prototype.sendToHost = function (cmd, dataObj, callback) {
        var tTAN = this.generateTAN();
        this.callbackList[tTAN] = callback;
        // send the request
        window.parent.window.postMessage({
            cmd: cmd,
            data: dataObj,
            transactionCode: tTAN,
        }, this._recipient);
    };
    DriverWeb.prototype.detachListeners = function () {
        if (window.removeEventListener) {
            window.removeEventListener("message", this.listenerFromHost, false);
        }
        else if (window["detachEvent"]) {
            window["detachEvent"]("onmessage", this.listenerFromHost);
        }
    };
    DriverWeb.ALNUMCHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    return DriverWeb;
}(IDriver_1.IDriver));
exports.DriverWeb = DriverWeb;
