/*
 * 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, node: true, plusplus: true, devel: true, nomen: true, indent: 4, bitwise: true */
/*global  */
"use strict";

var $                       = require("jquery"),
    _                       = require("underscore"),
    Q                       = require("q"),
    Backbone                = require("backbone"),
    Strings                 = require("./LocStrings"),
    Template                = require("./TemplateLoader"),
    SemiModalDialogView     = require("./semiModalDialogView.js"),
    AssetButtonBarView      = require("./assetButtonBarView.js"),
    Headlights              = require("./utils/Headlights"),
    DefaultSettingsModel    = require("./defaultSettingsModel.js");


var SettingsDialogView = SemiModalDialogView.extend({
    template: _.template(Template.loadTemplate("../templates/settingsDialogView.html")),
    events: {
        "change .checklist li input[type='checkbox']": "updateScaleOuput",
        "blur .checklist li input[type='text']": "handleBlur"
    },
    initialize: function (options) {
        this.stashedViewValues = new Backbone.Model();
        this.resetViewValues();
        _.extend(this.events, SemiModalDialogView.prototype.events);
        this.listenTo(this.model, "default-names-changed", this.resetViewValues);
        this.listenTo(this.model, "change", this.appyChangesToStash);
        this.listenTo(this.stashedViewValues, "change", this.renderStashedChanges);
    },
    render: function (options) {
        SemiModalDialogView.prototype.render.call(this, options);
        this.renderAllStashedProperties();
        /*
        this.buttonBar = new AssetButtonBarView({
            model: this.model,
            className: "button-bar",
            isEditable: false
        });
        this.buttonBar.standardButtonAction = this.updateDesignAt.bind(this);
        this.$(".resolution h3").after(this.buttonBar.render().$el);
       */
    },
    show: function (evt) {
        this.resetViewValues();
        return SemiModalDialogView.prototype.show.call(this, evt);
    },
    updateDesignAt: function ($button) {
        this.buttonBar.deselectAll();
        this.model.set("designedAt", $button.attr("data-val"));
    },
    logIfResolutionsChanged: function () {
        var anyChanged = false,
            attrName;

        for (attrName in DefaultSettingsModel.prototype.defaultSizeLookup) {
            if (DefaultSettingsModel.prototype.defaultSizeLookup.hasOwnProperty(attrName) &&
                    this.model.get(attrName) !== this.stashedViewValues.get(attrName)) {
                anyChanged = true;
                break;
            }
        }
             
        if (anyChanged) {
            Headlights.logEvent(Headlights.CREMA_ACTION, Headlights.CHANGED_RES_SETTINGS);
        }
    },
    doAction: function (code) {
        if (code === "OK") {
            this.logIfResolutionsChanged();
            this.commitViewValues();
            this.hide();
        } else if (code === "Cancel") {
            this.hide();
        }
    },
    handleBlur: function (e) {
        var input = $(e.currentTarget);
        if (input.val()) {
            this.updateCheckbox(input.attr("data-assigned-value"));
        }
    },
    commitViewValues: function () {
        this.syncModels(this.stashedViewValues, this.model);
        this.model.trigger("default-names-changed", {ignoreSender: this});
    },
    appyChangesToStash: function (model, options) {
        if (options && options.ignoreSender === this) {
            return;
        }
        this.syncModels(this.model, this.stashedViewValues);
    },
    resetViewValues: function () {
        this.syncModels(this.model, this.stashedViewValues);
    },
    renderAllStashedProperties: function () {
        var attrs = this.stashedViewValues.attributes;
        _.each(Object.keys(attrs), this.updateStashedProperty, this);
    },
    renderStashedChanges: function (model, options) {
        if (options && options.ignoreSender === this) {
            return;
        }
        var attrs = this.stashedViewValues.changedAttributes() || this.stashedViewValues.attributes;
        _.each(Object.keys(attrs), this.updateStashedProperty, this);
    },
    updateStashedProperty: function (key) {
        var val = this.stashedViewValues.get(key),
            sizeKey;
        if (key.indexOf("text_") === 0) {
            var pair = this.model.getFolderSuffixObject(val),
                subKey = key.substr(5);
            sizeKey = this.model.defaultSizeLookup[subKey];
            this.updateFolderInput(sizeKey, pair.folder);
            this.updateSuffixInput(sizeKey, pair.suffix);
        } else {
            if (this.model.defaultSizeLookup && _.has(this.model.defaultSizeLookup, key)) {
                sizeKey = this.model.defaultSizeLookup[key];
            } else {
                sizeKey = key;
            }
            this.updateCheckbox(sizeKey, val);
        }
    },
    updateFolderInput: function (key, value) {
        this.$("input[type='text'][name='folder']").filter("[data-assigned-value='" + key + "']").val(value);
    },
    updateSuffixInput: function (key, value) {
        this.$("input[type='text'][name='suffix']").filter("[data-assigned-value='" + key + "']").val(value);
    },
    updateUserSettings: function (values) {
        Object.keys(values).forEach(function (key) {
            //existances means we can check this thing
            this.updateFolderInput(key, values[key].folder);
            this.updateSuffixInput(key, values[key].suffix);
            this.updateCheckbox(key);
        }, this);
    },
    updateCheckbox: function (value, checked) {
        if (!_.isBoolean(checked)) {
            checked = true;
        }
        var checkbox = this.$("input[type='checkbox']").filter("[value='" + value + "']");
        checkbox.prop("checked", checked);
        checkbox.change();
    },
    syncModels: function (source, target, options) {
        var targetKeys = Object.keys(target.attributes),
            sourceKeys = Object.keys(source.attributes),
            keysToRemove = _.difference(targetKeys, sourceKeys);
        _.each(keysToRemove, function (key) {
            target.unset(key, options);
        });
        target.set(source.attributes, options);
    },
    updateScaleOuput: function (e) {
        var checkbox = $(e.currentTarget),
            isChecked = checkbox.prop("checked"),
            input = checkbox.closest("li").find("input[type='text']"),
            stashKey = checkbox.val(),
            modelKey,
            stash = {};
        
        if (_.has(this.model.sizeDefaultLookup, stashKey)) {
            modelKey = _.first(this.model.sizeDefaultLookup[stashKey]);
        } else {
            modelKey = stashKey;
        }
        
        input.each(function () {
            var inputVal = "",
                val = "",
                $input = $(this);
            if (isChecked) {
                inputVal = $input.val().trim();
                if (inputVal && inputVal !== "/") {
                    val = $input.val();
                } else {
                    val = $input.attr("placeholder");
                }
                if (val === "none") {
                    val = "";
                    $input.attr({"placeholder": ""});
                }
                stash[$input.attr("name")] = val;
            } else {
                var placeholder = $input.attr("placeholder"),
                    data = $input.attr("data-placeholder") || "none";
                if (placeholder === "") {
                    $input.attr({"placeholder": data});
                }
            }
            $input.val(val);
        });
        
        var modelVals = {};
        modelVals[modelKey] = isChecked;
        modelVals["text_" + modelKey] = this.model.getExportString(stash);
        this.stashedViewValues.set(modelVals, {ignoreSender: this});
    }
});

module.exports = SettingsDialogView;
