// (C) Copyright 2020 Hewlett-Packard Enterprise Company, L.P.
define(['hp/view/DialogView',
        'hp/core/EventDispatcher',
        'hp/core/Environment',
        'hp/core/Localizer',
        'fs/presenter/status/StatusPresenter',
        'hp/presenter/settings/FactoryResetPresenter',
        'fs/view/status/StatusPager',
        'hp/core/Router',      
        'jquery'],

function(DialogView, EventDispatcher, environment, localizer, statusPresenter, 
        factoryResetPresenter, statusPager, router ) {"use strict";

    var StatusErrorView = ( function() {

        var CONSOLE_DETAILS_ID = '#hp-error-console-details';
        var BROADCAST_DETAILS_ID = '#hp-error-broadcast-details';
        var RESTART_LINK_ID = '#hp-error-restart-link';
        var FACTORY_RESET_OPTION_ID = '#hp-error-factory-reset-option';
        var FACTORY_RESET_LINK_ID = '#hp-error-factory-reset-link';
        var SUPPORT_DUMP_LINK_ID = '#hp-error-support-dump-link';
        
        var RESTART_FAILURE_DIALOG_ID = '#hp-error-restart-failure-dialog';

        var SUPPORT_DUMP_FAILURE_DIALOG_ID = '#hp-error-support-dump-failure-dialog';
        var SUPPORT_DUMP_CONFIRMATION_DIALOG_ID = "#hp-error-support-dump-confirmation-dialog";
        var FACTORY_RESET_FAILURE_DIALOG_ID = '#hp-error-factory-reset-failure-dialog';
        var FACTORY_RESET_CONFIRMATION_DIALOG_ID = "#hp-error-factory-reset-confirmation-dialog";
        
        var ALWAYS_ENCRYPT = true;
        
        /**
         * @class View script for the /status/error page
         */
        function StatusErrorView() {
            
            
            var restartFailureDialog;

            var supportDumpFailureDialog;
            var supportDumpConfirmationDialog;
            var factoryResetFailureDialog;
            var factoryResetConfirmationDialog;
            
            var checkDownloadDelay = 3000;
            var timeout = null;
            
            var dispatcher = new EventDispatcher();
            
            /**
             * Callback for when the call to restart the appliance fails.  Show a dialog with a generic error message.
             */
            function handleRestartError(e) {
                // show the user a dialog with a generic error message
                dispatcher.fire('restartFailure');
            }

            function restartAppliance() {
                
                statusPresenter.rebootAppliance({
                    error: handleRestartError,
                    success: function () {}
                    
                });
                //statusPager.unload("status error"); //unload the current page
                statusPager.load("status waiting", true); // load waiting page 
                
            }
            
            function onFactoryResetFailure(errorInfo) {
                dispatcher.fire('factoryResetFailure');
                
                /*
                 * TODO: Figure out how these failures should be reported.
                 * 
                 * When the UX team comes up with new mocks, if those new mocks call for a more complicated error
                 * page that does support some kind of notifications area, then this module should be updated to
                 * depend on NotificationsView and something like the following should be included here.

                var factoryResetError = {
                    summary : localizer.getString('fs.settings.factoryReset.startFailure'),
                    status : "error"
                };
                notifications.add(factoryResetError, true, true, true);
                */
            }

            function onFactoryResetSuccess(result) {
               statusPresenter.setFactoryReset(true);
               router.go("/status", "waiting for factory reset to finish"); 
            }

            function startFactoryReset() {
                factoryResetPresenter.startFactoryReset('RECOVERY', { 
                    success: function(result) {
                        onFactoryResetSuccess(result);
                    },                
                    error: onFactoryResetFailure
                });                                          
            }

            function createSupportDump() {
                statusPresenter.createSupportDump(ALWAYS_ENCRYPT);
            }

            /**
             * Callback function when the call to create support dump fails. Show a dialog with a generic error message.
             */
            function onCreateSupportDumpError(data) {
                dispatcher.fire('supportDumpFailure');
            }

            /**
             * Callback function when the call to create support dump succeeds.
             * Once support dump is created, automatically download it.
             * @param data
             */
            function onCreateSupportDumpSuccess(data) {
                var link = document.getElementById("hiddenDownloader");
                if(link===null){
                    $('<a>',{
                        id: 'hiddenDownloader',
                        style: {display: 'none'}
                        }).appendTo('body');
                }
                $('#hiddenDownloader').attr("href",data);
                $('#hiddenDownloader').click(function(){
                    window.location = $('#hiddenDownloader').attr('href');
                });
                clearTimeout(timeout);
                 timeout= setTimeout(function () {
                    statusPresenter.checkDownloadLink(data,{
                    success:function() {
                        $('#hiddenDownloader').trigger('click');
                    },
                    error:function() {
                        onCreateSupportDumpError(data);
                    }
                    });
                }, checkDownloadDelay);
            }

            function registerEvents() {
                statusPresenter.on("createDumpSuccess", onCreateSupportDumpSuccess);
                statusPresenter.on("createDumpError", onCreateSupportDumpError);
            }
            
            function showFactoryResetOption() {
                // TODO: Isolate infrequent case where isKioskMode() == false on console.
                // alert("environment.isKioskMode() == " + environment.isKioskMode());
                return ( environment.isKioskMode() && !factoryResetPresenter.factoryResetDisabled() );
            }
            
            function initRestartFailureDialog() {
                function open() {
                    var dialogView = null;
                    dialogView = new DialogView({contents: restartFailureDialog});
                    restartFailureDialog.show();
                }
                
                restartFailureDialog = $(RESTART_FAILURE_DIALOG_ID).detach();
                
                dispatcher.on('restartFailure', open);
            }
            
            function initSupportDumpFailureDialog() {
                function open() {
                    var dialogView = null;
                    dialogView = new DialogView({contents: supportDumpFailureDialog});
                    supportDumpFailureDialog.show();
                }
                
                supportDumpFailureDialog = $(SUPPORT_DUMP_FAILURE_DIALOG_ID).detach();
                
                dispatcher.on('supportDumpFailure', open);
            }
            function initSupportDumpConfirmationDialog() {
                function confirm() {
                    createSupportDump();
                }
                function open() {
                    var dialogView = null;
                    dialogView = new DialogView({ok: confirm, contents: supportDumpConfirmationDialog});
                    supportDumpConfirmationDialog.show();
                }
                
                supportDumpConfirmationDialog = $(SUPPORT_DUMP_CONFIRMATION_DIALOG_ID).detach();
                
                $(SUPPORT_DUMP_LINK_ID).on('click', open);
            }
            
            function initFactoryResetFailureDialog() {
                function open() {
                    var dialogView = null;
                    dialogView = new DialogView({contents: factoryResetFailureDialog});
                    factoryResetFailureDialog.show();
                }
                
                factoryResetFailureDialog = $(FACTORY_RESET_FAILURE_DIALOG_ID).detach();
                
                dispatcher.on('factoryResetFailure', open);
            }
            function initFactoryResetConfirmationDialog() {
                function confirm() {
                    startFactoryReset();
                }
                function open() {
                    var dialogView = null;
                    dialogView = new DialogView({ok: confirm, contents: factoryResetConfirmationDialog});
                    factoryResetConfirmationDialog.show();
                }
                
                // according to the latest mocks, factory reset is not available on the error page
                factoryResetConfirmationDialog = $(FACTORY_RESET_CONFIRMATION_DIALOG_ID).detach();
                
                if (showFactoryResetOption()) {
                    $(FACTORY_RESET_LINK_ID).on('click', open);
                }
            }
            
            this.pause = function() {
                restartFailureDialog.hide();
                supportDumpFailureDialog.hide();
                supportDumpConfirmationDialog.hide();
                factoryResetFailureDialog.hide();
                factoryResetConfirmationDialog.hide();
            };

            this.resume = function() {
                document.title = localizer.getString('fs.status.error.title');
            };
            this.init = function() {
                
                statusPresenter.init();
                registerEvents();
                
                document.title = localizer.getString('fs.status.error.title');
                
                $(RESTART_LINK_ID).on('click', restartAppliance);   // No confirmation - just do it.
                initRestartFailureDialog();
                initSupportDumpFailureDialog();
                initSupportDumpConfirmationDialog();
                // according to the latest mocks, factory reset is not available on the error page
                initFactoryResetFailureDialog();
                initFactoryResetConfirmationDialog();
                
                if (environment.isKioskMode()) {
                    // do not allow support dump in the kiosk mode as it will not work
                    $(BROADCAST_DETAILS_ID).hide();
                    $(SUPPORT_DUMP_LINK_ID).hide();  
                    if (factoryResetPresenter.factoryResetDisabled()) {
                         $(FACTORY_RESET_OPTION_ID).hide();
                    }                 
                } else {
                    $(CONSOLE_DETAILS_ID).hide();
                }
            };
        }

        return new StatusErrorView();

    }());

    return StatusErrorView;

});
