// (C) Copyright 2020 Hewlett-Packard Enterprise Company, L.P.
define(['hp/core/Localizer', 'hp/presenter/EulaPresenter', 'hp/core/Router',
    'hp/view/DialogView', 'text!hpPages/login/eula-confirmation.html',
    'hp/core/Banner',
    'hp/view/FormStateView', 'hp/core/Notifications',
    'jquery', 'hp/lib/jquery.hpToggle', 'lib/jquery.validate'],

function(localizer, presenter, router, DialogView, eulaconfirmation,
    banner, FormStateView, notifications) { "use strict";

    var EulaView = (function() {

        var AGREE_BUTTON = "#hp-eula-agree-button",
            OK_BUTTON = "#hp-eula-ok-button",
            DISAGREE_BUTTON = "#hp-eula-disagree-button",
            EULA_HEADER_TITLE_TWO = "#hp-header-eula-type",
            EULA_WRITTEN_OFFER = "#hp-eula-partnercontent-body",
            EULA_SUPPORT_ACCESS = "#hp-eula-supportaccess-body",
            EULA_CONTENT_BODY = "#hp-eula-contents-body",
            EULA_SERVICE_TOGGLE = '#hp-eula-service-access-toggle-button';
        var APPLIANCE_NAME = '#hp-header-eula-name';
        var CONFIRMATION_APPLIANCE_NAME = '#hp-eula-confirmation-appliance-name';
        var EULA_IFRAME = "#iframe-eula-content";
        var EULA_IFRAME_UPGRADE = "#iframe-eula-upgrade";
        var SPINNER = ".hp-spinner-image";
        var EULA_AGREE_DISAGREE_MESSAGE = "#hp-eula-agree-disagree-message-body";
        var EULA_YES_DISAGREE_BUTTON = '#eula-confirmation-disagree-button';
        var EULA_CANCEL_BUTTON = '#eula-confirmation-cancel-button';
        var SUPPORT_ACCESS_WARNING ='#hp-support-access-warning';
        var FORM = '#hp-eulamain-form';

        function EulaView() {
            var formStateView = new FormStateView();

            function onToggleButtonChange(){
                if ($(EULA_SERVICE_TOGGLE).is(':checked')) {
                    $(SUPPORT_ACCESS_WARNING).hide();
                } else {
                    $(SUPPORT_ACCESS_WARNING).show();
                }
            }
            
            function onLoadSupportSuccess(data, status, xhr){
                $(EULA_IFRAME).hide();
                var applicationSuppportHtml = $(data).filter('#hp-eula-appliancesupport-content');
                localizer.localizeDom(applicationSuppportHtml);
                $(EULA_CONTENT_BODY).empty();
                $(EULA_CONTENT_BODY).append(applicationSuppportHtml);

                var supportAccessHtml = $(data).filter('#hp-eula-supportaccess-content');
                localizer.localizeDom(supportAccessHtml);
                $(EULA_SUPPORT_ACCESS).empty();
                $(EULA_SUPPORT_ACCESS).append(supportAccessHtml);
                $(EULA_SERVICE_TOGGLE).hpToggle({
                    checked: localizer.getString('fs.settings.eula.config.enabled'),
                    unchecked: localizer.getString('fs.settings.eula.config.disabled')
                });
                $(EULA_SERVICE_TOGGLE).change(onToggleButtonChange);
                var writtenOfferHtml = $(data).filter('#hp-eula-partner-content');
                localizer.localizeDom(writtenOfferHtml);
                $(EULA_WRITTEN_OFFER).empty();
                $(EULA_WRITTEN_OFFER).html(writtenOfferHtml);
                
                presenter.checkIsSupportEnabled();
            }

            function onLoadSupportError(jqXHR, textStats, errorThrown) {
            }
            
            function loadSupportPageHtml() {
                var url = localizer.getString('fs.settings.eula.config.content_directory') + "/" +
                    localizer.getString('fs.settings.eula.config.support_access_file');
                $.ajax({
                    url: url,
                    type: 'GET',
                    async: true,
                    dataType: "html",
                    success: onLoadSupportSuccess,
                    error: onLoadSupportError
                });
            }
            
            function onDisagreeButtonClick(){
                var dialogView = null;
                dialogView = new DialogView({
                contents:eulaconfirmation,
                    ok : function(){
                        window.parent.close(); // Works only with IE, closing the browser Tab
                    }
                });
                $(CONFIRMATION_APPLIANCE_NAME).html(banner.getApplicationTitle());
                $(EULA_YES_DISAGREE_BUTTON).html(localizer.getString('core.details.ok'));
                $(EULA_CANCEL_BUTTON).hide();
            }

            function onAgreeButtonClick(){
                $(EULA_HEADER_TITLE_TWO).text(localizer.getString
                    ('fs.settings.eula.config.end_user_support_title'));
                loadSupportPageHtml();
                $(OK_BUTTON).show();
                $(AGREE_BUTTON).hide();
                $(DISAGREE_BUTTON).hide();
                $(EULA_AGREE_DISAGREE_MESSAGE).hide();
            }

            function onOkButtonClick() {
                if ($(FORM).valid()) {
	                var isSupportEnabled = false;
	                if ($(EULA_SERVICE_TOGGLE).is(':checked')) {
	                    isSupportEnabled = true;
	                }
	                presenter.saveEulaStatus(isSupportEnabled);
                }
            }

            function isSupportEnabledSuccess(isSupportEnabled) {
                if (isSupportEnabled) {
                    $(EULA_SERVICE_TOGGLE).attr("checked", "checked");
                    $(SUPPORT_ACCESS_WARNING).hide();
                } else {
                    $(EULA_SERVICE_TOGGLE).removeAttr("checked");
                    $(SUPPORT_ACCESS_WARNING).show();
                }
                $(EULA_SERVICE_TOGGLE).trigger('change');
            }

            function isSupportEnabledFailure(errorMessage) {
                var errorDetail = JSON.stringify(errorMessage.message);
                errorDetail = errorDetail.replace(/["']{1}/gi,"");
                var message = localizer.getString('fs.settings.supportaccess.service_unavailable');
                var notif = {
                        summary : message,
                        status : 'error',
                        details : errorDetail
                    };
                formStateView.setMessage(notif);
                notifications.add(notif, true);
                $(EULA_SERVICE_TOGGLE).removeAttr("checked");
                $(EULA_SERVICE_TOGGLE).trigger('change');
            }

            function onSaveEulaSuccess(data) {
                router.go('/login', 'on Eula accepted');
            }

            function onSaveEulaFailed(errorMsg) {
                router.go('/eula','on Eula failed');
            }

            function loadEulaMainHtml(){
                $(EULA_IFRAME).show();
            }

            function removeEvents() {
                presenter.off("isSupportEnabledSucess", isSupportEnabledSuccess);
                presenter.off("isSupportEnabledFailure",isSupportEnabledFailure);
                presenter.off("saveEulaSucess", onSaveEulaSuccess);
                presenter.off("saveEulaFailed", onSaveEulaFailed);
            }

            function registerEvents() {
                presenter.on("isSupportEnabledSucess", isSupportEnabledSuccess);
                presenter.on("isSupportEnabledFailure",isSupportEnabledFailure);
                presenter.on("saveEulaSucess", onSaveEulaSuccess);
                presenter.on("saveEulaFailed", onSaveEulaFailed);
            }

            this.pause = function() {
                removeEvents();
                $(SPINNER).show();
            };

            this.resume = function(){
                $(EULA_IFRAME_UPGRADE).hide();
                $(EULA_HEADER_TITLE_TWO).text(localizer.getString
                    ('fs.settings.eula.config.end_user_title'));
                $(EULA_CONTENT_BODY).empty();
                $(EULA_WRITTEN_OFFER).empty();
                $(EULA_SUPPORT_ACCESS).empty();
                loadEulaMainHtml();
                $(OK_BUTTON).hide();
                $(DISAGREE_BUTTON).show();
                $(AGREE_BUTTON).show();
                $(EULA_AGREE_DISAGREE_MESSAGE).show();
                registerEvents();
                $(SPINNER).hide();
            };

            this.init = function() {
                formStateView.init({form: FORM,autoTrack: true});
                var eulaContentFileByLanguage = localizer.getString('fs.settings.eula.config.content_directory') + "/" +
                    localizer.getString('fs.settings.eula.config.eula_content_file');
                $(EULA_IFRAME).attr('src', eulaContentFileByLanguage);
                $(EULA_IFRAME_UPGRADE).hide();
                $(APPLIANCE_NAME).text(banner.getApplicationTitle());
                loadEulaMainHtml();
                $(AGREE_BUTTON).click(onAgreeButtonClick);
                $(DISAGREE_BUTTON).click(function(ev) {
                    onDisagreeButtonClick();
                    ev.preventDefault();
                });
                $(OK_BUTTON).click(onOkButtonClick);
                registerEvents();
                $(SPINNER).hide();
            };
        }

        return new EulaView();

    }());

    return EulaView;

});
