/*
 * 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 */
/*global define: true, graphite: true, window: true */
define(
    [
        'jquery',
        'underscore',
        'backbone',
        'plugin-dependencies',              // plugin dependencies from ccweb
        'ccweb.files.extract/models/PluginConfigModel',
        'ccweb.files.extract/models/PluginAuthModel',
        'ccweb.files.extract/models/MetricsProxyModel',
        'ccweb.files.extract/models/UserSettingsModel',
        'ccweb.files.extract/models/PSDSettingsModel',
        'ccweb.files.extract/views/detail/PSDDetailsView',    // main view file
        'ccweb.files.extract/controllers/InterceptController',
        'ccweb.files.extract/controllers/AssetController',    // controller to populate a PSDModel with graphite JSON
        'ccweb.files.extract/serverAPI',
        'css!override/../css/topcoat.css',
        'css!override/../css/firstUserExp.css',
        'css!override/../css/jobListing.css',
        'css!override/../css/inspect.css',
        'css!override/../css/layers.css',
        'css!override/../css/main.css',
        'css!override/../css/popup.css',
        'css!override/../css/preview.css',
        'css!override/../css/zIndex.css',
        'css!override/../css/mobile.css'
    ],

    function ($, _, Backbone, deps, PluginConfigModel, PluginAuthModel, MetricsProxyModel, UserSettingsModel,
              PSDSettingsModel, PSDDetailsView, InterceptController, AssetController, serverAPI) {
        'use strict';

        // Make sure we have a global graphite object and that it has the serverAPI
        window.graphite = window.graphite || {};
        window.graphite.events = window.graphite.events || _.extend({}, Backbone.Events);

        window.graphite.serverAPI = serverAPI;
        //set Feature Enabled
        window.graphite.fflags = window.graphite.fflags || {};
        window.graphite.setFeatureEnabled = function (aFeatureName, bFeatureEnabled) {
            if (aFeatureName !== null) {
                window.graphite.fflags[aFeatureName] = bFeatureEnabled;
            }
        };

        window.graphite.configModel = new PluginConfigModel();
        window.graphite.authModel = new PluginAuthModel();
        window.graphite.metricsProxyModel = new MetricsProxyModel();

        if (window.graphite.metricsProxyModel) {
            window.graphite.metricsProxyModel.setAuthModel(window.graphite.authModel);
            window.graphite.metricsProxyModel.setConfigModel(window.graphite.configModel);
        }

        graphite.events.trigger('register-defaults');

        //isFeatureEnabled
        window.graphite.isFeatureEnabled = function (aFeatureName) {
            var bFeatureEnabled = false;
            if (aFeatureName !== null) {
                if (window.graphite.fflags[aFeatureName]) {
                    bFeatureEnabled = true;
                }
            }
            return bFeatureEnabled;
        };

        window.graphite.inPublicOneUp = function () {
            return deps.utils.getCurrentBasePath() === 'link';
        };

        var prevAssetGuid,
            extractPSDModel;

        return function (model) {
            var modelId = model.get('id'),
                assetGuid = modelId.substr(modelId.lastIndexOf('/') + 1),
                layerCompId = model.get("layerCompId"),
                path = model.get("path"),
                md5 = model.get('md5'),
                welcomeExp = model.get('welcomeExp');

            window.graphite.urlBase = modelId.substr(0, modelId.indexOf('/api/'));
            window.graphite.ownerId = model.get('ownerId');
            window.graphite.linkId = model.get('linkId');

            if (this) {
                this.localContent = model.get('localContent') || false;
            }

            if (prevAssetGuid !== assetGuid) {
                extractPSDModel = AssetController.getAsset(assetGuid,
                    layerCompId,
                    function () {
                        if (window.graphite.metricsProxyModel.authModel.isAnalyticsOptIn()) {
                            InterceptController.applyBehaviors();
                        }
                    },
                    function (response) {
                        if (response.status === 401) {
                            graphite.events.trigger('reauthenticate');
                        }
                    },
                    this);
                PSDSettingsModel.setup(assetGuid);
                prevAssetGuid = assetGuid;
            }

            extractPSDModel = AssetController.getAsset(assetGuid,
                md5,
                layerCompId,
                function () {
                    //Since we are not using the data we capture from the Intercepts, I'm commenting this for now. 
//                    if (window.graphite.metricsProxyModel.authModel.isAnalyticsOptIn()) {
//                        InterceptController.applyBehaviors();
//                    }
                },
                function (response) {
                    if (response.status === 401) {
                        graphite.events.trigger("reauthenticate");
                    }
                },
                this, path, welcomeExp);

			// Propagate a few additional attributes of the asset model
            // we received from our plugin host (if applicable).
            extractPSDModel.set('modified', model.get('modified'));
            extractPSDModel.set('assetId', model.get('id'));
            extractPSDModel.set('fileName', model.get('name'));
            extractPSDModel.set('type', model.get('type'));
            extractPSDModel.set('height', model.get('height'));
            extractPSDModel.set('width', model.get('width'));

            var INTERFACE = {
                $el: $('<div>').addClass('extract-plugin'),

                show: function () {
                    if (window.graphite.inPublicOneUp()) {
                        this.$el.addClass('public');
                    }
                    this.psdDetailsView = new PSDDetailsView({model: extractPSDModel});
                    this.$el.html(this.psdDetailsView.$el);
                    this.addHandlers();
                },

                hide: function () {
                    graphite.events.trigger('reset-layers-visibility');
                    if (this.psdDetailsView) {
                        this.psdDetailsView.remove();
                        this.psdDetailsView = null;
                    }
                    this.removeHandlers();
                    extractPSDModel.reset();
                },

                addHandlers: function () {
                    graphite.events.on('layerCompChanged', this.layerCompChanged, this);
                },

                removeHandlers: function () {
                    graphite.events.off('layerCompChanged', this.layerCompChanged, this);
                },

                layerCompChanged: function (model) {
                    this.hide();
                    extractPSDModel = model;
                    this.show();
                    this.trigger('added-to-dom');
                },

                trigger: function (event) {
                    if (event === 'added-to-dom') {
                        if (this.psdDetailsView.previewView) {
                            this.psdDetailsView.previewView.attached();
                        }
                    }
                },

                sizeChange: function () {

                }
            };


            return INTERFACE;
        };
    }
);
