"use strict";
var EXPORTED_SYMBOLS = ["module"];
var module = function (container) {
var log = function (message) {
container.api.logger.trace("[External Interface] " + message);
}
;
var ExternalInterface = function () {
this._observer = null;
this._handlers = {
};
this._defaultHandler = null;
this._externalIsReady = false;
this._queue = [];
}
;
ExternalInterface.prototype = {
constructor: ExternalInterface,
finalize: function () {
this._observer = null;
this._handlers = {
};
}
,
addHandler: function (subject, handler) {
if ("string" != typeof subject || "function" != typeof handler)
{
return;
}

var subjectHandlers = this._handlers[subject];
if ("undefined" == typeof subjectHandlers)
{
subjectHandlers = this._handlers[subject] = [];
}

subjectHandlers.push(handler);
}
,
addDefaultHandler: function (handler) {
if ("function" != typeof handler)
{
return;
}

this._defaultHandler = handler;
}
,
setExternalReadyState: function (isReady) {
this._externalIsReady = isReady;
if (true === isReady)
{
this.sendQueuedMessages();
}

}
,
sendToExternal: function (subject, data) {
if ("function" != typeof this._observer || false === this._externalIsReady)
{
this._queue.push({
subject: subject,
data: data});
}
 else
{
log("Sent to external\n" + subject + " " + data);
this._observer.call(null,subject,data);
}

}
,
sendQueuedMessages: function () {
var queue = this._queue;
var queueLength = queue.length;
if (0 === queueLength)
{
return;
}

for (let i = 0;i < queueLength;i++) {
let message = queue[i];
log("Sent to external from queue\n" + message.subject + " " + message.data);
this._observer.call(null,message.subject,message.data);
}

}
,
setExternalHandler: function (observer) {
if ("function" != typeof observer)
{
log("Attempt to set external handler failed. Provided object in not a function.");
return;
}

log("Observer registered " + observer);
this._observer = observer;
}
,
sendMessage: function (subject, string) {
var subjectHandlers = this._handlers[subject];
if ("undefined" == typeof subjectHandlers && null === this._defaultHandler)
{
return;
}

subjectHandlers = subjectHandlers || [this._defaultHandler];
var data = string;
try {
data = JSON.parse(string);
}
catch (e) {

}

subjectHandlers.forEach(function (handler) {
handler.call(null,subject,data);
}
);
}
};
return ExternalInterface;
}
;
