/*
 * 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, document: true*/

define([
    'jquery',
    'underscore',
    'backbone',
    'parfait/LayerItemView',
    'DWPSDExtractManager',
    'ccweb.files.extract/controllers/SelectionController',
    'ccweb.files.extract/utils/KeyboardUtils'
], function ($, _, Backbone, LayerItemView, DWPSDExtractManager, SelectionController, KeyboardUtils) {
    "use strict";
    
    var DwLayerItemView = LayerItemView.extend({
        initialize: function (options) {
            // TODO: Base class code. See if base class method can be used
            _.bindAll(this,
                'handleVisibilityToggleClick',
                'handleThumbMouseEnter',
                'handleThumbMouseLeave');

            this.model.set('psdGuid', options.psdGuid);
            this.model.set('toplevel', options.toplevel);
            this.parentView = options.parentView;
            this.render();
            if (!window.graphite.routers.main.isWelcomeExpDismissed()) {
                this.$el.find(".asset-button").addClass("disabled");
            } else {
                this.$el.find(".asset-button").removeClass("disabled");
            }
            this.$el.find('.image-wrapper').first().on('mouseenter', this.handleThumbMouseEnter);
            this.$el.find('.image-wrapper').first().on('mouseleave', this.handleThumbMouseLeave);
            this.$el.find('.visible-button').first().on('click', this.handleVisibilityToggleClick);
            this.addHandlers();
            
            _.bindAll(this, "handleMouseDownEvent", "handleMouseUpEvent");
            this.$el.find(".image-wrapper").first().on("mousedown", this.handleMouseDownEvent);
            this.$el.find(".image-wrapper").first().on("mouseup", this.handleMouseUpEvent);
        },
        
        handleMouseEnter: function () {
            LayerItemView.prototype.handleMouseEnter.apply(this, arguments);
			// The below function will check for weather we are online or
			// not.
            if (!DWPSDExtractManager.canEnableDownloadAssets()) {
                this.$el.find(".asset-button").addClass("disabled");
            } else {
                this.$el.find(".asset-button").removeClass("disabled");
            }
        },
        
        addHandlers: function () {
            LayerItemView.prototype.addHandlers.apply(this, arguments);
            window.graphite.events.on("netstatus-change", function (notification) {
                var extractIcon = this.$el.find(".asset-button");
                if (notification === "reconnected" && DWPSDExtractManager.isAssetExtractAvailable()) {
                    extractIcon.removeClass('disabled');
                } else {
                    extractIcon.addClass('disabled');
                }
            }, this);
        
        },
        
        handleSelectionChange: function () {
            if (this.$el.hasClass('selected')) {
                this.$el.removeClass('selected');
                if (this.parentView) {
                    this.parentView.childSelected(false);
                }
            }
            if (this.model.get('selected') === true) {
                this.$el.addClass('selected');
                if (this.model.canBeExtracted()) {
                    this.$el.find('.layer-item').addClass('show-export');
                }
                if (this.parentView) {
                    this.parentView.childSelected(true);
                    this.parentView.expand();
                    this.parentView.scrollIntoView();
                }
            } else {
                this.$el.find('.layer-item').removeClass('show-export');
            }
        },
        
        
        handleMouseDownEvent: function (event) {
            if (event.button === 2) {
                this.logCanvasClick("rightClick", event.clientX, event.clientY);
            } else if (event.button === 0) {
                var page = { x: event.pageX, y: event.pageY },
                    self = this;
                $(window).on("mousemove.dragDetect", function (event) {
                    self.isClickDrag = true;
                    if (Math.abs(event.pageX - page.x) > 3 || Math.abs(event.pageY - page.y) > 3) {
                        var hitItem = self.model;
                        if (hitItem) {
                            var hitLayerId = hitItem.get("layerId");
                            var layerIds = [hitLayerId];
                            var layerName = hitItem.get("layerName");
                            var selectedLayers = SelectionController.getSelectedLayers();
                            // Check and merge with current selection.
                            if (selectedLayers.length > 0) {
                                var selLayerIds = [];
                                selectedLayers.forEach(function (layer) {
                                    selLayerIds.push(layer.get("layerId"));
                                });
                                // selection exists and hit item is a part of selected items
                                // so take the multiple selection. 
                                if (selLayerIds.indexOf(hitLayerId) !== -1) {
                                    layerIds = selLayerIds;
                                } else if (KeyboardUtils.isMultiSelectKey(event)) {
                                    // Or if the selection key is still pressed, merge the hit item
                                    // with the selected items.
                                    layerIds = layerIds.concat(selLayerIds);
                                }
                            }
                            DWPSDExtractManager.startDrag("dFEV", JSON.stringify(layerIds), DWPSDExtractManager.normalizeFileName(layerName)); // also pass the current layercomps
                            // ask dreamwever to drag the layer ids
                            graphite.events.trigger("canvasClickDrag");
                            $(window).off(".dragDetect");
                        }
                    }
                });
            }
        },
        
        handleLayerSelect: function (event) {
            LayerItemView.prototype.handleLayerSelect.apply(this, arguments);
            graphite.events.trigger("layers-usage", {formatSubEvent : ["LayerSelected"]});
        },
        
        handleVisibilityToggleClick: function (event) {
            LayerItemView.prototype.handleVisibilityToggleClick.apply(this, arguments);
            if (event) {
                var visible = this.model.get('visible'),
                    visibilityChangedTo = "HideLayer";
                if (visible) {
                    visibilityChangedTo = "ShowLayer";
                }
                graphite.events.trigger("layers-usage", {formatSubEvent : [visibilityChangedTo]});
            }
        },
        
        handleMouseUpEvent: function (event) {
            $(window).off(".dragDetect");
            this.isClickDrag = false;
        },
        
        removeEventListeners: function () {
            this.$el.find(".image-wrapper").first().off("mouseenter", this.handleThumbMouseEnter);
            this.$el.find(".image-wrapper").first().off("mouseleave", this.handleThumbMouseLeave);
            this.$el.find(".visible-button").first().off("click", this.handleVisibilityToggleClick);
            this.model.off(null, null, this);
            graphite.events.off(null, null, this);
        },
        
        remove: function () {
            this.$el.find(".image-wrapper").first().off("mousedown", this.handleMouseDownEvent);
            this.$el.find(".image-wrapper").first().off("mouseup", this.handleMouseUpEvent);
            this.undelegateEvents();
            this.unbind();
            this.stopListening();
            LayerItemView.prototype.remove.apply(this, arguments);
        }
    });

    return DwLayerItemView;
});
