/*
 * ADOBE CONFIDENTIAL
 *
 * Copyright (c) 2014 Adobe Systems Incorporated. All rights reserved.
 *
 * NOTICE:  All information contained herein is, and remains
 * the property of Adobe Systems Incorporated and its suppliers,
 * if any.  The intellectual and technical concepts contained
 * herein are proprietary to Adobe Systems Incorporated and its
 * suppliers and are protected by trade secret or copyright law.
 * Dissemination of this information or reproduction of this material
 * is strictly forbidden unless prior written permission is obtained
 * from Adobe Systems Incorporated.
 */

/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, bitwise: true, node: true */
/*global define: false, graphite: false, require: false, $: true, module: false,  localeStrings: false, csInterface: true, CSEvent: true */

"use strict";
var _ = require("underscore");

var PhotoshopCallback = function(csEvent) {
    var callback;
    try {
        // Check to make sure it's for us.
        //TODO this seems to be failing now, extensionId is an empty string.
        // if (csEvent.extensionId === csInterface.getExtensionID()) {
        //     if (csEvent.data) {
        //         photoshopDelegate.invoke(+csEvent.data.split(",")[0], csEvent);
        //     }
        // }
        if (csEvent.data) {
            photoshopDelegate.invoke(+csEvent.data.split(",")[0], csEvent);
        }
    } catch (err) {
        console.log("PSCallback error: " + err);
    }
};


var PhotoshopDelegate = function() {
    this._eventMap = [];
};


PhotoshopDelegate.prototype.invoke = function(eventID, csEvent) {
    var callback = this._eventMap[eventID];
    if(callback) {
        callback(csEvent);
    }
};

PhotoshopDelegate.prototype._registerEvent = function() {

    csInterface.addEventListener("PhotoshopCallback", PhotoshopCallback);

    var event = new CSEvent("com.adobe.PhotoshopRegisterEvent", "APPLICATION");
    event.extensionId = csInterface.getExtensionID();
    event.data = Object.keys(this._eventMap).join(", ");
    csInterface.dispatchEvent(event);
};



PhotoshopDelegate.prototype.addEvents = function(event) {
   /* if(!_.isArray(events)) {
        events = [events];
    }
    */
        csInterface.evalScript( "app.stringIDToTypeID('"+ event.name + "');",
                            function(result) {
                                this._eventMap[+result] = event.delegate;
                                this._registerEvent();
                            }.bind(this) );
};

var photoshopDelegate = new PhotoshopDelegate();
module.exports = photoshopDelegate;