/*
 * 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 */
/*global define: true, graphite: true, window: true, document: true*/

define([
    'jquery',
    'underscore',
    'backbone',
    'ccweb.files.extract/utils/TemplateUtil',
    'ccweb.files.extract/controllers/ZoomController',
    'ccweb.files.extract/controllers/SelectionController',
    'ccweb.files.extract/controllers/AssetController',
    'text!ccweb.files.extract/views/templates/layerCompsTemplate.html',
    'plugin-dependencies',
    'parfait/LayerCompView'
], function ($, _, Backbone, TemplateUtil, ZoomController, SelectionController, AssetController, LayerCompsTemplate, deps, LayerCompView) {
    'use strict';
    var DwLayerCompView = LayerCompView.extend({
        initialize: function () {
            _.bindAll(this, "handleMouseDown", "requestLayerComp");
            graphite.events.on("layerCompsLoaded", this.handleLayerCompsLoaded, this);
            $(document).off("mousedown.layerComps");
            $(document).on("mousedown.layerComps", this.handleMouseDown);
            window.graphite.events.on("dismiss-context-menu", this.dismissContextMenu, this);
            window.graphite.events.on('document-mousedown', this.handleMouseDown, this);
            this.render();
        },
        
        remove: function () {
            graphite.events.off(null, null, this);
            this.$el.empty();
            $(document).off("mousedown.layerComps");
            return Backbone.View.prototype.remove.apply(this, arguments);
        },
        
         handleLayerCompsLoaded: function () {
            var psdModel = SelectionController.getPSDModel(),
                layerComps = SelectionController.getPSDModel().get("layerComps"),
                appliedComp = psdModel.get("imgdata").appliedLayerCompId || 0,
                lastDocLabel = deps.translate('LAST_DOCUMENT_STATE'),
                currentLayerComp,
                currentCompIndex;

            this.$el.empty();
            if (layerComps && (layerComps.length > 0)) {

                // Append pseudo layer item (Last Document State).
                if (layerComps[0].get('name') !== lastDocLabel) {
                    layerComps.unshift(new Backbone.Model({name: lastDocLabel, id: 0}));
                }

                // Setup template data.
                currentLayerComp = _.find(layerComps, function (item) {
                    return item.id === appliedComp;
                });
                currentLayerComp = currentLayerComp || layerComps[0];
                currentCompIndex = layerComps.indexOf(currentLayerComp);

                this.$el.html(TemplateUtil.createTemplate(LayerCompsTemplate,
                    {layerComps: layerComps, currentIndex: currentCompIndex}));
                graphite.events.trigger('layerCompChangeComplete');
                
                $('#breadcrumbs ul li').first().addClass('less-width');
            }
        },
        
        handleActivate: function (event) {
            this.$el.find("#layerCompDropdown").toggleClass('active');
            window.addEventListener('mousedown', this.handleDocumentMouseDown, true);
            return false;
        },

        handleDocumentMouseDown: function (evt) {
            window.graphite.events.trigger("document-mousedown", evt);
        },
        
        handleMouseDown: function (event) {
            var $target = $(event.target);
            if (!$target.is(this.$el) && this.$el.find($target).length === 0) {
                this.dismissContextMenu();
            }
        },

        dismissContextMenu: function () {
            window.removeEventListener('mousedown', this.handleDocumentMouseDown, true);
            $('#layerCompDropdown').removeClass('active');
        },
        
        handleSelectOption: function (event) {
            var psdModel = SelectionController.getPSDModel(),
                appliedComp = psdModel.get('imgdata').appliedLayerCompId,
                $selection = $(event.target),
                selectedId = parseInt($selection.attr('id'), 10);
            
            if (selectedId !== appliedComp) {
                psdModel.get('imgdata').appliedLayerCompId = selectedId;
                this.handleLayerCompsLoaded();
                _.defer(this.requestLayerComp, selectedId);
            }
            this.dismissContextMenu();
            event.stopPropagation();
            event.preventDefault();
        },

        requestLayerComp: function (selectedId) {
            var oldModel = SelectionController.getPSDModel(),
                psdModel;
            graphite.events.trigger("layerCompChanging");
            graphite.events.trigger("layerComp-dropdown-used");
            this.$el.find("#layerCompDropdown").addClass("disabled");
            psdModel = AssetController.getAsset(oldModel.id, oldModel.md5, selectedId,
                function () {
                    // Notify, while giving animated progress indicator a chance
                    // to reflect a fully complete status.
                    _.delay(function () {
                        graphite.events.trigger('layerCompChanged', psdModel);
                    }, 500);
                },
                function () {}, this, oldModel.get("path"), !window.graphite.routers.main.isWelcomeExpDismissed());
        }
    });
    
    return DwLayerCompView;
});