
/*
 * ADOBE CONFIDENTIAL
 *
 * Copyright (c) 2013-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, setTimeout: true, XMLHttpRequest: true*/

define([
    'jquery',
    'underscore',
    'backbone',
    'plugin-dependencies',
    'controllers/AuthController',
    'utils/TemplateUtil',
    'controllers/ThumbnailController',
    'parfait/AssetView',
    'dreamweaver/utils/CommonUtil'
], function ($, _, Backbone, deps, AuthController, TemplateUtil, ThumbnailController, AssetView, CommonUtil) {
    "use strict";
    var DwAssetView = AssetView.extend({
        render: function () {
            try {
                var tmplId;
                if (this.model.get("fileToLoad") !== undefined) {
                    if (CommonUtil.typeMatchDirectory(this.model.get('type'))) {
                        this.$el.addClass("asset-folder");
                        tmplId = "#asset-folder-view-template";
                    } else {
                        tmplId = "#asset-view-loading-template";
                    }
                } else {
                    if (CommonUtil.typeMatchDirectory(this.model.get('type'))) {
                        this.$el.addClass("asset-folder");
                        tmplId = "#asset-folder-view-template";
                    } else if (CommonUtil.typeMatchUpload(this.model.get('type'))) {
                        tmplId = "#asset-upload-view-template";
                    } else {
                        tmplId = "#asset-view-template";
                        //Call out to see if this file is still processing. This can happen if the UI is refreshed
                        //while one or more PSDs are being processed.
                        //this.checkStatus();
                    }
                }
                var el = this.$el;
                el.html(TemplateUtil.createTemplate(tmplId, this.model.toJSON()));

                var elem = el.find(".assetThumbnail");
                if (elem[0]) {
                    ThumbnailController.drawThumbnail(this.model, elem[0]);
                }

                if (this.getGraphiteWorker()) {
                    this.$('.image-wrapper-progress').removeClass("asset-uploading").addClass("asset-processing");
                    this.$('#progressbar').removeClass("progressbar-uploading").addClass("progressbar-processing");
                }

            } catch (err) {
                console.log("Failed to render thumb for:" + this.model.attributes.name);
            }
            return this;
        },
        
        hideWelcomePageCallback: function (forceHide) {
			window.graphite.ignoreWelcomeScreen = true;
			window.graphite.extractHiddenWelcomePage = forceHide;
			var uploadPSDElelment = $('.grid article.card-asset .uploadAssetContainer')[0],
				rect = uploadPSDElelment.getBoundingClientRect(),
				argsObj = {};
			
			argsObj.x = rect.left + 1;
			argsObj.y = rect.bottom - 1;
			
			window.dwPSDExtractManager.clickInExtractPanel(argsObj);
			
			window.document.body.onfocus = function () {
                if (!window.graphite.persistentDrawers) {
                    var paramsObj = {};
                    paramsObj.panelPersistentDrawer = false;
                    window.dwPSDExtractManager.setOWLBoolUsePersistentDrawer(paramsObj);
                }

				argsObj = {};
				argsObj.callback = function () {
					window.graphite.extractHiddenWelcomePage = false;
					window.graphite.ignoreWelcomeScreen = false;
				};
				
				if (window.graphite.extractHiddenWelcomePage === true) {
					window.dwPSDExtractManager.showWelcomePageIfNeeded(argsObj);
				}
				window.document.body.onfocus = null;
			};
        },
        
        _hideWelcomePageIfNeeded: function () {
            var argsObj = {};
            argsObj.callback = this.hideWelcomePageCallback;
            window.dwPSDExtractManager.hideWelcomePageOnUpload(argsObj);
        },
                
        handleUploadAsset: function () {
            if (!window.graphite.extractHiddenWelcomePage && window.graphite.ignoreWelcomeScreen !== true) {
                var argsObj = {};
                argsObj.callback = function (persistentDrawers) {
                    window.graphite.persistentDrawers = persistentDrawers;
                    if (!persistentDrawers) {
                        var args = {};
                        args.panelPersistentDrawer = true;
                        window.dwPSDExtractManager.setOWLBoolUsePersistentDrawer(args);
                    }
                };
                window.dwPSDExtractManager.getOWLBoolUsePersistentDrawer(argsObj);
                
                this._hideWelcomePageIfNeeded();
            } else {
                graphite.events.trigger("psd-upload-initiated");
                $('#gridContainer').find('input[name="uploadPSD"]').trigger('click');
                $(window.document.body).focus();
				window.graphite.ignoreWelcomeScreen = false;
            }
        },
        
        assetClickHandler: function (event) {
            var self = event.data.self;
            if (AuthController.isLoggedIn()) {
                if (!self.model.get("uploadProgress")) {
                    if (CommonUtil.typeMatchDirectory(self.model.attributes.type)) {
                        var location = Backbone.history.fragment || "files";
                        Backbone.history.navigate(location + "/" + self.model.get("name"), true);
                    } else if (CommonUtil.typeMatchSupportedPSD(self.model.attributes.type)) {
                        if (window.graphite.routers.main.folderShared["#" + Backbone.history.fragment] === true) {
                            graphite.events.trigger("sharedPsdThumbnailClick");
                        } else {
                            graphite.events.trigger("psdThumbnailClick");
                        }
                        
                        var url = "asset/psd/" + self.model.get("id").replace(/\//g, "_") + "/" + self.model.get("md5").replace(/\//g, "_").replace(/\,/g, "_") + "/" + (self.model.get("assetLocation") || "files");
                        url = url +  "/" + self.model.get("name");
                        url = url.replace(/\/\//g, "/"); // remove dupe slashes
                        url = encodeURI(url);
                        Backbone.history.navigate(url, true);
                    } else if (CommonUtil.typeMatchUpload(self.model.attributes.type)) {
                        //If spinner is visible, ignore click on upload button.
                        if (!$('#loadingSpinner').is(":visible")) {
                            self.handleUploadAsset();
                        }
                        return false;
                    }
                }
            } else {
                // DPO - I can't work out when or how this method gets fired.
                // There was an alert here before. This would never get shown, because it's not an alert.
                graphite.events.trigger('load-alert', deps.translate("NO_LONGER_LOGGED_IN_LOGIN_AGAIN"));
                window.location.href = window.location;
            }
        },
        
        handleRightClick : function (event) {
            var self = event.data.self;
            if (CommonUtil.typeMatchSupportedPSD(self.model.attributes.type)) {
                if (event.button === 2) {
                    graphite.events.trigger("psdThumbnailRightClick");
                }
            }
            
        },
        
        addHandlers : function () {
            graphite.events.on("uploaded", this.showUploadedAssetPreview, this);
            
            var that = this;
            this.$el.mouseenter(function () {
                $(that.el).find(".del-button").css("visibility", "visible");
                $(that.el).find(".del-button").click(function (event) {
                    graphite.serverAPI.deleteAsset(that.model.id,
                        that.handleDeleteSuccess,
                        that.handleDeleteError,
                        that);
                    event.stopImmediatePropagation();
                });
            });

            this.$el.mouseleave(function () {
                $(that.el).find(".del-button").css("visibility", "hidden");
            });

            this.$el.off('click', this.assetClickHandler).on('click', { self : this }, this.assetClickHandler);
            this.$el.off('mousedown', this.handleRightClick).on('mousedown', {self: this}, this.handleRightClick);
        },

        showUploadedAssetPreview: function (params) {
            var self = this;
            if (this.model.get('name') === params.fileName) {
                var path = params.path || '';
                path = encodeURI(path);
                var fetchOptions = graphite.serverAPI.createAjaxOptions('GET',  path + "/:metadata");
                $.ajax({
                    type: "GET",
                    url: fetchOptions.url,
                    headers: fetchOptions.headers
                }).done(function (msg) {
                    self.model.set(msg);
                    self.model.unset('fileToLoad');
                    var date = new Date(self.model.attributes.created);
                    self.model.attributes.date = window.dwPSDExtractManager.getFormattedDateTime(date);
                    date = null;
                    self.render();
                    self.addHandlers();
                });
            }
        }
    });
    return DwAssetView;
});
