define(['bluebird'], function () {
    var Promise = require('bluebird');

    var ChildWidget = function() {
        this.init();
    };

    ChildWidget.prototype.init = function() {
        var self = this;
        self.settings = {};

        window.addEventListener("message", function(event) {
            return self.onMessage(event);
        }, false);
    };

    ChildWidget.prototype.sendMessage = function(message) {
        var str = JSON.stringify(message);
        //console.log('Child: Send:', str);
        window.parent.postMessage(str, '*');
    };

    ChildWidget.prototype.onMessage = function(event) {
        var self = this;
        if (event.source === window.parent.parent || event.source === window.parent) {
            try {
                //console.log('Child: Received:', event.data);
                var data = JSON.parse(event.data);
                switch(data.widgetAction) {
                    case 'load': self.load(data.settings); break;
                    case 'play': self.play(); break;
                }
            } catch(e) {
                // !ignore any json errors
            }
        }
    };

    ChildWidget.prototype.sendInitialized = function(settings) {
        var self = this;
        self.sendMessage({ widgetEvent: 'initialized' });
    };

    ChildWidget.prototype.load = function(settings) {
        var self = this;
        self.settings = settings;
        if (typeof self.onload === 'function') {
            self.onload();
        }
    };

    ChildWidget.prototype.setLoaded = function(settings) {
        var self = this;
        self._loaded = true;
        self.sendMessage({ widgetEvent: 'loaded' });
    };

    ChildWidget.prototype.play = function() {
        var self = this;
        if (typeof self.onplay === 'function') {
            self.onplay();
        }
    };

    ChildWidget.prototype.setPlayed = function(settings) {
        var self = this;
        self._played = true;
        self.sendMessage({ widgetEvent: 'played' });
    };

    return ChildWidget;
});
