/*
 * 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, bitwise: true */
/*global define: true, graphite: true, unescape: true, localStorage: true, window: true, navigator: true, dwPSDExtractManager: true*/

define([
    'jquery',
    'underscore',
    'backbone',
    'models/AuthModel',
    'plugin-dependencies',
    'views/landing/AssetListView',
    'dreamweaver/controllers/DwNetworkStatusController',
    'dreamweaver/views/DwConnectionAlertToolbarView',
    'dreamweaver/views/FirstScreenView',
    'views/landing/WaitListView',
    'controllers/AuthController',
    'controllers/LandingPageController',
    'override/dwCcwebMain',
    'DWPSDExtractManager',
    'ccweb.files.extract/views/preview/PSDPreviewView'
], function ($, _, Backbone, AuthModel, deps, AssetListView, DwNetworkStatusController, DwConnectionAlertToolbarView, FirstScreenView,
             WaitListView, AuthController, LandingPageController, ExtractPlugin, DWPSDExtractManager, PSDPreviewView) {
    "use strict";
        
    var ApplicationRouter = Backbone.Router.extend({

        authModel : null,
        isWelcomeExpLaunched: false,
        folderShared : {},
        
        routes: {
            "asset/psd/:id/:md5/*route": "handleAsset",
            "files/*route": "folderRoute",
            "*other": "defaultRoute"
        },

        showExtractPlugin: function (assetId, layerCompId, localContent) {
            if (this.extractPlugin) {
                this.extractPlugin.hide();
            }
            var self = this,
                $results;
            
            if (dwPSDExtractManager.isDWPSDExtractManagerInitialized()) {
                // create a shim that looks like ccweb's asset_model.js with an id attribute.
                var asset_model = new Backbone.Model({id: "/" + assetId, localContent: localContent, layerCompId: layerCompId});
                this.extractPlugin = new ExtractPlugin(asset_model);
                $results = $('#results');
                $results.html(this.extractPlugin.$el);
                this.extractPlugin.show();
                return;
            }
            
            // Show some default view while dreamweaver is setting up Parfait Usage
            if (this.isWelcomeExpDismissed()) {
                this.firstScreenView = new FirstScreenView();
                $results = $('#results');
                $results.html(this.firstScreenView.$el);
            }
        },


        showExtractPsdPlugin: function (assetId, md5, layerCompId, path, welcomeExp) {
            if (this.extractPlugin) {
                this.extractPlugin.hide();
            }
            var self = this, $results;
            
            if (dwPSDExtractManager.isDWPSDExtractManagerInitialized() || !this.isWelcomeExpDismissed()) {
                // create a shim that looks like ccweb's asset_model.js with an id attribute.
                var asset_model = new Backbone.Model({id: assetId, assetId: assetId, md5: md5, layerCompId: layerCompId, path: path, welcomeExp: welcomeExp});
                this.extractPlugin = new ExtractPlugin(asset_model);
                $results = $('#results');
                $results.html(this.extractPlugin.$el);
                this.extractPlugin.show();
                return;
            }
            
            // Show some default view while dreamweaver is setting up Parfait Usage
            if (this.isWelcomeExpDismissed()) {
                this.firstScreenView = new FirstScreenView();
                $results = $('#results');
                $results.html(this.firstScreenView.$el);
            }
        },

        initialize: function () {
            this.authModel = new AuthModel();
            AuthController.setAuthModel(this.authModel);
            var browserWarning = deps.translate("BROWSER_INFO");
            graphite.events.trigger('register-defaults');
            this.networkMonitor = new DwNetworkStatusController();
            this.networkMonitor.startListening();
            if (!AuthController.getAuthModel().isValid()) {
                $("body").addClass("not-logged-in");
                this.destroyViews(["assetListView"]);
                LandingPageController.onLandingPage = true;
                LandingPageController.setLandingPage();
                this.showExtractPlugin(LandingPageController.getLandingPageDirectory(), null, LandingPageController.getLandingPage());
                    // Commenting the drawPreviewFinish event for Landing page. 
                    // This turns off the event handler for download popup in rendering view
                    // I am keeping this code as we may need it for making the landing view
//                graphite.events.on('drawPreviewFinish', function () {
//                    LandingPageController.establishBehavior();
//                });

                //trigger landing-page event
                graphite.metricsProxyModel.setDefaultParam('landingPageConfiguration', LandingPageController.getMetricsSegment());

            } else {
                LandingPageController.onLandingPage = false;
            }
        },
        
        _handleAsset: function (assetId, md5, path, welcomeExp) {
            if (AuthController.getAuthModel().isValidWithUserFeature() || welcomeExp) {
                $("#draganddropmessage").hide();
                this.destroyViews(["assetListView"]);
                this.showExtractPsdPlugin(assetId, md5, '', path, welcomeExp);
            } else {
                this.defaultRoute();
            }
        },
        
        handleAsset: function (assetId, md5, path) {
            var self = this;
            graphite.events.trigger('route-change', 'handleAsset');
            DWPSDExtractManager.refreshContextMenu();
            
            $('#loadingSpinner').show();
            
            var fetchOptions = graphite.serverAPI.createAjaxOptions('GET',  "/" + encodeURI(path) + "/:metadata");
            $.ajax({
                type: "GET",
                url: fetchOptions.url,
                headers: fetchOptions.headers,
                cache: false
            }).done(function (metadata) {
                $('#loadingSpinner').hide();
                md5 = metadata.md5.replace(/\//g, "_").replace(/\,/g, "_");
                self._handleAsset(assetId, md5, path);
            }).fail(function (jqXHR, textStatus) {
                $('#loadingSpinner').hide();
                self._handleAsset(assetId, md5, path);
            });
        },

        folderRoute: function (path) {
            
            if (this.extractPlugin) {
                this.extractPlugin.hide();
            }
            graphite.events.trigger('route-change', 'folderRoute');
            DWPSDExtractManager.refreshContextMenu();
            
            if (AuthController.getAuthModel() && AuthController.getAuthModel().isValid()) {
                if (AuthController.getAuthModel().user_data.accountEnabled) {
                    if (!this.connectionAlertToolbarView) {
                        this.connectionAlertToolbarView = new DwConnectionAlertToolbarView();
                    }
                    this.destroyViews(["assetListView", "firstScreenView"]);
                    $("body").removeClass("not-logged-in");
                    this.assetListView = new AssetListView(AuthController.getAuthModel(), path);
                    $("#draganddropmessage").show();

                } else {
                    this.waitListView = new WaitListView(AuthController.getAuthModel());
                }
            } else {
                $("#draganddropmessage").hide();
            }
            
        },

        defaultRoute: function () {
            Backbone.history.fragment = '';
            DWPSDExtractManager.refreshContextMenu();
            if (!this.isWelcomeExpDismissed()) {
                $("body").removeClass("not-logged-in");
                if (!this.isWelcomeExpLaunched) {
                    this.isWelcomeExpLaunched = true;
                    this._handleAsset("WelcomeExp", "WelcomeExp", "welcome/", true);
                }
            } else {
                if (this.extractPlugin) {
                    this.extractPlugin.hide();
                }
            
                graphite.events.trigger('route-change', 'defaultRoute');

                if (AuthController.getAuthModel() && AuthController.getAuthModel().isValid() && navigator.onLine) {
                    if (AuthController.getAuthModel().user_data.accountEnabled) {
                        if (!this.connectionAlertToolbarView) {
                            this.connectionAlertToolbarView = new DwConnectionAlertToolbarView();
                        }
                        this.destroyViews(["assetListView", "firstScreenView"]);
                        $("body").removeClass("not-logged-in");
                        this.assetListView = new AssetListView(AuthController.getAuthModel());

                        $("#draganddropmessage").show();
                    } else {
                        this.waitListView = new WaitListView(AuthController.getAuthModel());
                    }
                } else {
                    $("#draganddropmessage").hide();
                }
            }
        },
        isWelcomeExpDismissed: function () {
            //If window.dwData is still not initialized (which should not happen as it gets inited right at the start, but we have the check here to ensure consistent behavior) , just return true. It'll send the extract panel  through the normal mode of action in defaultRoute.
            return window.dwData ? window.dwData.isWelcomeExpDismissed === "true" : true;
        },
        setIsWelcomeExpDismissed: function (dismissed) {
            window.dwData.isWelcomeExpDismissed = dismissed;
            DWPSDExtractManager.setWelcomeExpDismissed(dismissed);
        },
        destroyViews: function (views) {
            var self = this;
            _.each(views, function (view) {
                if (self.hasOwnProperty(view)) {
                    self[view].remove();
                    delete self[view];
                }
            });
        }

    });

    return ApplicationRouter;
});
