/*
 * ADOBE CONFIDENTIAL
 *
 * Copyright (c) 2013 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 */
/*global define: true, graphite: true, Image: true, window: true*/

define([
    'jquery',
    'underscore',
    'backbone',
    'serverAPI',
    'ccweb.files.extract/Constants',
    'parfait/DetailsController',
    'dwconfig'
], function ($, _, Backbone, serverAPI, Constants, DetailsController, dwconfig) {
    "use strict";
    var DwDetailsController = $.extend(DetailsController, {
        setPSDModel: function (model) {
            var key;
            this.psdModel = model;
            // create new sprite sheet map when a new model is set
            for (key in this.spriteSheets) {
                if (this.spriteSheets.hasOwnProperty(key)) {
                    this.spriteSheets[key] = null;
                }
            }
            this.spriteSheets = {};
            this.spritesLoaded = {};
            this.spriteSheetLoadedEvent = null;

        },
        
        drawSpriteSheet: function (sheetID, drawFunc, context) {
            var image = this.spriteSheets[sheetID],
                that = this;
            if (image !== undefined && image !== null) {
                if (this.spritesLoaded[sheetID]) {
                    // Draw sprite sheet
                    drawFunc(image);
                } else {
                    // put this on the list of things to draw
                    image.drawWhenFinished.push(drawFunc);
                }
            } else {
            /*
            {
                
                image = new Image();
                image.drawWhenFinished = [drawFunc];
                this.spriteSheets[sheetID] = image;

                var imgURL = this.getSpriteSheetURL(sheetID);
                image.addEventListener('load', function () {
                    var thatImage = this;
                    that.spritesLoaded[sheetID] = true;
                    this.drawWhenFinished.forEach(function (data) {
                        data(thatImage);
                    });
                    if (that.spriteSheetsLoaded()) {
                        that.triggerSpriteSheetLoadedEvent();
                    }
                }, false);
                this.spritesLoaded[sheetID] = false;
                image.src = imgURL;
            }
            */
                image = new Image();
                graphite.serverAPI.applyCrossDomainPolicy(image);
                this.spriteSheets[sheetID] = image;
                image.drawWhenFinished = [drawFunc];
                var pathSeparator  = '/',
                    path = "files",
                    md5 = this.psdModel.get("md5"),
                    layerCompId = this.psdModel.get("layerCompId"),
                    welcomeExp = this.psdModel.get("welcomeExp"),
                    jsonVersion = window.graphite.spritesheetJsonVersion;
                
                if (!welcomeExp) {
                    path = window.dwData.configPath + path + pathSeparator;
                    jsonVersion = jsonVersion.replace(/\./g, "_"); //Replace all the '.'s with '_'
                    path +=  md5 + "/spritesheets/v_" + jsonVersion + pathSeparator + "sheet" + sheetID + "_" + layerCompId + ".png";
                } else {
                    path = window.dwData.programConfigPath + pathSeparator + dwconfig.WELCOME_EXP_PATH + pathSeparator;
                    path +=  md5 + "/sheet" + sheetID + "_" + layerCompId + ".png";
                }
                
                var url = this.getSpriteSheetURL('');
                
                var assetLocation = this.psdModel.get("pngLocation");
                if (!_.isEmpty(assetLocation)) {
                    var sheet = 'sheet' + sheetID;
                    if (assetLocation.hasOwnProperty(sheet)) {
                        url = this.getSpriteSheetURL(assetLocation[sheet]);
                    }
                }
                
                var onAssetAvailable = function (imgurl) {
                    image.addEventListener("load", function () {
                        var thatImage = this;
                        that.spritesLoaded[sheetID] = true;
                        this.drawWhenFinished.forEach(function (data) {
                            data(thatImage);
                        });
                        if (that.spriteSheetsLoaded()) {
                            that.triggerSpriteSheetLoadedEvent();
                        }
                    });
                    image.src = imgurl;
                };
                if (!welcomeExp) {
                    serverAPI.downloadWebAsset(url, onAssetAvailable, path);
                } else {
                    onAssetAvailable(path);
                }
                this.spritesLoaded[sheetID] = false;
            }
        },
        
        setSelectedTab: function (tab) {
            if (this.get("selectedTab") !== tab) {
                this.set("selectedTab", tab);
            } else {
                this.set("selectedTab", "");
            }
        },
        
        getSpriteSheetURL: function (location) {
            var url,
                localContent = this.psdModel.get('localContent'),
                sheetID = '';
            if (localContent) {
                url = localContent.directory + '/spritesheet/' + sheetID + ".png"; //dead code. Has been kept as it is to enable default PSD rendering.
            } else {
                url = graphite.serverAPI.getSpriteSheetURL(location);
            }
            return url;
        },
        
        triggerSpriteSheetLoadedEvent: function (overrideEventName) {
            graphite.events.trigger('hideWorkerProgress', -1);
            var eventName = overrideEventName || this.spriteSheetLoadedEvent;
            if (eventName === 'drawPreviewFinish' && this.spriteSheetsLoaded()) {
                $('.preview-loading-spinner').remove();
            }
            this.spriteSheetLoadedEvent = null;
            if (eventName) {
                graphite.events.trigger(eventName, this.psdModel);
            }
        }
    });
    return DwDetailsController;
});
