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

"use strict";

var Backbone = require('backbone'),
    $  = require("jquery"),
    _  = require("underscore"),
    Strings = require("./LocStrings"),
    Template = require("./TemplateLoader"),
    GenSettingView = require("./genSettingView.js");

var GenableView = Backbone.View.extend({
    initialize: function () {
        var settings = this.model.get("layerSettings");
        this.listenTo(this.model, "change:name", this.updateName);
        this.listenTo(this.model, "change:selected", this.handleSelection);
        this.listenTo(this.model, "change:isActive", this.handleActiveChange);
        this.listenTo(settings, "remove", this.removeSettingsView);
        this.listenTo(settings, "add", this.renderGenSettings);
        this.listenTo(settings, "refresh", this.renderGenSettings);
        this.listenTo(settings, "change:extension", this.renderFileFormat);
        this.listenTo(settings, "change:scale change:canvasWidth change:canvasHeight change:originalDimensions", this.renderDimensions);
        this._renderedSettings = [];
    },
    events: {
        "click .layer": "selectLayerClicked",
    },
    tagName: "li",
    template: _.template(Template.loadTemplate("../templates/genableView.html")),
    render: function () {
        var context,
            previewModel = this.model.getActivePreview();
        
        context = Template.createTemplateContext(Strings, {
            name: this.model.get("name"),
            size: this.getDimensionsString(),
            extension: previewModel && previewModel.getFileExtension() || ""
        });
        
        this.$el.html(this.template(context));
        this.$fileformat = this.$(".fileformat");
        this.$dimensions = this.$(".dimensions");
        this.$layer = this.$(".layer");
        this.$elName = this.$("span.title");
        this.$arrow = this.$(".asset .disclosure-arrow");
        this.$derived = this.$(".derived-assets");
        this.$thumbnail = this.$(".thumbnail-img");
        if (this.model.get("compId")) {
            this.$(".thumbnail").hide();
        }
        this.renderGenSettings();
        this.handleSelection();
 
        if (this.model.get("layerSettings").size() === 0) {
            this.$arrow.css({"visibility": "hidden"});
        }
        this.listenTo(this.model, "change:imageURL", this.renderThumbnail);
        if (this.model.get("imageURL")) {
            this.renderThumbnail();
        }
        return this;
    },
    renderFileFormat: function () {
        var previewModel = this.model.getActivePreview();
        this.$fileformat.text(previewModel && previewModel.getFileExtension() || "");
    },
    renderDimensions: function () {
        this.$dimensions.text(this.getDimensionsString());
    },
    getDimensionsString: function () {
        var previewModel = this.model.getActivePreview(),
            dim = previewModel && previewModel.getCanvasDimensions(),
            str = "";
        if (dim && dim.width && dim.height) {
            str = dim.width + " x " + dim.height;
        }
        return str;
    },
    handleActiveChange: function () {
        this.$layer.toggleClass("subselected", this.model.get("isActive") && !this.model.get("selected"));
    },
    handleSelection: function () {
        this.$layer.toggleClass("selected", this.model.get("selected"));
    },
    renderThumbnail: function () {
        if (!this.model.get("compId")) {
            this.$thumbnail.css({
                "background-image": "url('" + this.model.get("imageURL") + "')"
            });
        }
    },
    selectLayerClicked: function (e) {
        if (e.isDefaultPrevented()) {
            return;
        }
        if (!this.model.get("selected")) {
            this.ensureSelectedSetting(true);
        }
    },
    ensureSelectedSetting: function (selected) {
        this.model.set("selected", selected);
        this.model.get("layerSettings").trigger("parentSelectionChange", selected || this.model.get("isActive"));
    },
    removeSettingsView: function (model) {
        this._renderedSettings[model.cid].remove();
        this._renderedSettings[model.cid] = null;
    },
    renderGenSettings: function () {
        this.$derived.empty();
        this.model.get("layerSettings").forEach(function (itm) {
            if (itm.isSupported()) {
                var genSettingView = new GenSettingView({ model: itm });
                this.$derived.append(genSettingView.render().$el);
                this._renderedSettings[itm.cid] = genSettingView;
            }
        }, this);
    },
    updateName: function () {
        this.$elName.text(this.model.get("name"));
    }
});

module.exports = GenableView;
