define([

    "app",

    "modules/topMessagesControl",

    "custom-screens/IHConfiguration/system-network-configuration/system-network-configuration",
    "custom-screens/IHConfiguration/system-time-configuration/system-time-configuration",

], function (app, TopMessagesControl, SystemNetworkConfiguration, SystemTimeConfiguration) {

    var screenPosters = {
        GETTING_THINGS_READY: "GETTINGTHINGSREADY",
        WELCOME: "WELCOME",
        INITIAL_SETUP: "INITIALSETUP",
        CONFIGURING: "CONFIGURING",
        STARTING: "STARTING",
        RESET_TO_FACTORY_DEFAULTS: "RESETTOFACTORYDEFAULTS",
    };

    var actions = {
        RESET_TO_FACTORY_DEFAULTS: "RESETTOFACTORYDEFAULTS",
    }; 

    var refreshtout = null;
    var mainView = {
        i18n: null,
        currentScreen: null,
        processingNewConfig: false,
        currentAction: null,
        firstLoadMsgContainer: $('#first_load_msg_container'),
        mainScreenContainer: $('#main_screen'),
        processingPoster: $('#processing_poster'),
        resetToFactoryDefaultsPoster: $('#resetToFactoryDefaults_poster'),
        prevConfResultId: '',
        startBtn: $('#start_btn'),
        startingPoster: $('#starting_poster'),
        startingPosterBtn: $('#starting_poster_btn'),
        state: app.view_states.loading,
        sysNetworkConfigView: null,
        sysTimeConfigView: null,
        validationItemDatetime: $('#validation_item_datetime'),
        validationItemNetwork: $('#validation_item_network'),
        validationItemDatetimeMessages: $('#validation_item_datetime_messages_list'),
        validationItemNetworkMessages: $('#validation_item_network_messages_list'),
        welcomeMsgContainer: $('#welcome_msg_container'),

        callSystemTimeConfigurationService: function (action, options) {
            if (!options)
                options = {};
            if (!options.data)
                options.data = {};

            _.extend(options.data, { action: action, });

            var ajaxOpt = {
                async: true,
                type: 'POST',
            };

            _.extend(ajaxOpt, options);

            $.ajax(app.foldersRoot + '/landing/initConfig/api/systemInitialConfiguration.aspx', ajaxOpt);
        },
        checkConfigurationStatus: function () {
            var that = this;

            this.callSystemTimeConfigurationService(
                "GET_CONFG_OPER_STATUS",
                {
                    success: function (resp) {
                        try {
                            if ((resp != null) && (resp.Success == true) && (resp.Data != null)) {
                                var data = resp.Data;

                                var configurationStatus = data.ConfigurationStatus.toUpperCase(); 
                                switch (configurationStatus) {
                                    case "CONFIGURED":
                                        that.processingNewConfig = false;

                                        var settingThingsMsgContainer = $('#setting_things_msg_container');

                                        settingThingsMsgContainer.animate(
                                            { opacity: 0, },
                                            function () {
                                                settingThingsMsgContainer.hide();

                                                $('#starting_msg_container')
                                                    .show()
                                                    .animate(
                                                        { opacity: 1, },
                                                        function () {
                                                            var url = '../login/login.aspx';

                                                            setTimeout(
                                                                function () {
                                                                    window.location.href = url;
                                                                },
                                                                2000
                                                            );
                                                        }
                                                    );
                                            }
                                        );

                                        //Return to prevent call again this function.
                                        return;
                                        break;
                                    case "CONFIGURING":
                                        //that.startBtn.prop('disabled', true);
                                        break;
                                    case "NOTCONFIGURED":
                                        that.processingNewConfig = false;

                                        //that.startBtn.prop('disabled', false);

                                        //if ((resp.Data.PreviousConfigurationResult != null)
                                        break;
                                    case "UNKNOWN":
                                        that.processingNewConfig = false;

                                        //that.startBtn.prop('disabled', true);

                                        app.views.topMessages.showMessage(
                                            //that.i18n.translate('response_ok_change_apply').fetch()
                                            that.i18n.translate("Can not get status of system configuration. Check server's database connection.").fetch()
                                        );

                                        break;
                                    case "RESETTOFACTORYDEFAULTS":
                                        that.processingNewConfig = false;

                                        that.resetToFactoryDefaults();
                                        break;
                                    default:
                                        break;
                                }
                                
                                if (_.indexOf(["NOTCONFIGURED", "UNKNOWN"], configurationStatus) != -1
                                    && that.currentScreen != screenPosters.WELCOME
                                    && that.state == app.view_states.shown
                                    ) {
                                    clearTimeout(refreshtout); 
                                    that.showWelcomeMsg(); 
                                } else if (_.indexOf(["NOTCONFIGURED", "UNKNOWN"], configurationStatus) != -1
                                    && that.currentScreen != screenPosters.WELCOME) {

                                    refreshtout = setTimeout(function () { location.reload() }, 15000); 
                                }

                                if ((data.PreviousConfigurationResult != null) && (data.PreviousConfigurationResultId != null)) {
                                    var prevConfResult = data.PreviousConfigurationResult,
                                        currentPrevConfResultId = data.PreviousConfigurationResultId;

                                    if (prevConfResult != null) {
                                        if ((prevConfResult.Success == false) && (currentPrevConfResultId != that.prevConfResultId)) {
                                            that.show();

                                            that.hideProcessingPoster();

                                            that.updateValidationStatus();

                                            that.prevConfResultId = currentPrevConfResultId;

                                            app.views.topMessages.showMessage(that.i18n.translate(prevConfResult.Message).fetch());
                                        }
                                    }
                                }
                            }
                            else if (that.processingNewConfig == false) {
                                app.serverResponseToConsole(resp, true);
                            }
                        }
                        catch (Error) { console.error(Error); }

                        setTimeout(that.checkConfigurationStatus, 5000);
                    },
                    error: function (error) {
                        try {
                            if (that.processingNewConfig == false) {
                                app.views.topMessages.showMessage(
                                    that.i18n.translate("error").fetch()
                                );
                            }

                            setTimeout(that.checkConfigurationStatus, 10000);
                        }
                        catch (Error) { console.error(Error); }
                    }
                }
            );
        },
        getViewsAllData: function () {
            var configData = this.getViewsConfigData();

            return {
                networkEthernet: _.extend(
                    this.sysNetworkConfigView.subviews.ethernet.status.model.toJSON(),
                    configData.networkEthernet
                ),
                networkWifi: _.extend(
                    this.sysNetworkConfigView.subviews.wifi.status.model.toJSON(),
                    configData.networkWifi
                ),
                datetime: configData.datetime,
            };
        },
        getViewsConfigData: function () {
            return {
                datetime: this.sysTimeConfigView.model.toJSON(),
                networkEthernet: this.sysNetworkConfigView.subviews.ethernet.config.model.toJSON(),
                networkWifi: _.extend(
                    this.sysNetworkConfigView.subviews.wifi.config.model.toJSON(),
                    {
                        password: this.sysNetworkConfigView.subviews.wifi.status.model.get('password'),
                        ssid: this.sysNetworkConfigView.subviews.wifi.status.model.get('currentSSID'),
                    }
                ),
            };
        },
        hideResetToFactoryDefaultsPoster: function () {
            var that = this;

            this.resetToFactoryDefaultsPoster.animate(
                { opacity: 0, }
                , function () {
                    that.resetToFactoryDefaultsPoster.hide(); 
                }
            );
        }, 
        hideProcessingPoster: function () {
            var that = this;

            this.processingPoster.animate(
                { opacity: 0, },
                function () {
                    that.processingPoster.hide();
                }
            );
        },
        hideStartingPoster: function () {
            var that = this;

            if (this.state == app.view_states.shown) {
                this.startingPoster.animate(
                    { opacity: 0, },
                    function () {
                        that.startingPoster.hide();

                        $('#tz-footer-wrapper-container').show();
                    }
                );
            }
            else {
                setTimeout(this.hideStartingPoster, 100);
            }
        },
        hideAllPosters: function (callback) {
            var that = this;
            $(".big-poster").animate({ opacity: 0, }, function () {
                $(".big-poster").hide();
                callback.apply(that); 
            }); 
        }, 
        render: function () {
            var that = this;

            _.bindAll(this);

            app.views.topMessages = new TopMessagesControl.Views.Main({ el: $("#top_messages_bar_container") });
            app.views.topMessages.render();


            //Render first the starting poster objects
            this.startingPosterBtn.on('click', this.startingPosterBtn_click);

            this.sysNetworkConfigView = new SystemNetworkConfiguration.Views.Main({
                container: $('#network_config_view'),
                mode: SystemNetworkConfiguration.ViewModes.InitConfig,

                onappend: function () {
                    try {
                        console.log('reached onappend init config'); 
                        //this.sysNetworkConfigView.subviews.ethernet.config.on('edited', this.view_edited);
                        //that.sysNetworkConfigView.subviews.wifi.config.on('edited', that.view_edited);
                        that.sysNetworkConfigView.subviews.ethernet.config.model.on('change', that.view_model_change);
                        that.sysNetworkConfigView.subviews.ethernet.status.model.on('change', that.view_model_change);
                        that.sysNetworkConfigView.subviews.wifi.config.model.on('change', that.view_model_change);
                        that.sysNetworkConfigView.subviews.wifi.status.model.on('change', that.view_model_change);

                        that.show();
                    }
                    catch (Error) { console.error(Error); }
                }
            });
            this.sysNetworkConfigView.render();

            this.sysTimeConfigView = new SystemTimeConfiguration.Views.Main({
                container: $('#time_config_view'),
                onappend: function () {
                    try {
                        //this.sysTimeConfigView.on('edited', this.view_edited);
                        that.sysTimeConfigView.model.on('change', that.view_model_change);

                        that.show();
                    }
                    catch (Error) { console.error(Error); }
                }
            });
            this.sysTimeConfigView.render();

            this.startBtn.bind('click', this.startBtn_click);

            $(window).bind('beforeunload', this.window_beforeUnload);

            app.getI18NJed(
                this,
                "initConfig",
                function (i18nJED) {
                    try {
                        //storing internationalization data
                        that.i18n = i18nJED;

                        that.checkConfigurationStatus();
                    }
                    catch (Error) { console.error(Error); }
                }, 
                true, 
                "/landing/initConfig/"
            );
        },
        show: function () {
            var shownState = app.view_states.shown;

            if (this.state != shownState) {
                if ((this.sysNetworkConfigView.options.state == shownState)
                    && (this.sysTimeConfigView.options.state == shownState)) {
                    var that = this;

                    setTimeout(
                        function () {
                            console.log('reached to initial screen shown'); 
                            that.mainScreenContainer.removeClass('hide');

                            clearTimeout(refreshtout); 
                            that.state = shownState;
                            that.startingPosterBtn.removeClass('hide');
                        },
                        200
                    );
                }
            }
        },
        showProcessingPoster: function () {
            this.processingPoster
                .show()
                .animate({ opacity: 1, });
        },
        showWelcomeMsg: function () {
            var that = this;

            if (this.currentScreen != screenPosters.WELCOME) {
                this.currentScreen = screenPosters.WELCOME;

                this.startingPoster.show().css({ opacity: 1, });

                //possible poster being shown
                this.hideResetToFactoryDefaultsPoster(); 

                this.firstLoadMsgContainer.animate(
                    { opacity: 0, },
                    function () {
                        that.firstLoadMsgContainer.hide();

                        that.welcomeMsgContainer
                            .show()
                            .animate({ opacity: 1, });
                    }
                );
            }
        },
        resetToFactoryDefaults: function () {
            var that = this;

            if (this.currentAction != actions.RESET_TO_FACTORY_DEFAULTS) {

                this.currentScreen = screenPosters.RESET_TO_FACTORY_DEFAULTS; 
                this.currentAction = actions.RESET_TO_FACTORY_DEFAULTS;

                this.resetToFactoryDefaultsPoster.show().animate({ opacity: 1, });

                //this.callSystemTimeConfigurationService(
                //    "RESET_TO_FACTORY_DEFAULTS",
                //    {
                //        data: {
                //        },
                //        success: function (resp) {
                //            try {
                //            }
                //            catch (Error) { console.error(Error); }
                //        },
                //        error: function (error) {
                //            try {
                //                that.currentAction = null; 
                //                app.views.topMessages.showMessage('Temporaly server error. Try again please.');
                //            }
                //            catch (Error) { console.error(Error); }
                //        }
                //    }
                //);
            }
        }, 
        updateValidationStatus: function () {
            var data = this.getViewsAllData(),
                validation,
                valid = true;


            //*************
            //Network
            //*************
            validation = this.validateNetworkConfiguration(data);

            this.validationItemNetworkMessages.empty();
            if (validation.valid == true) {
                this.validationItemNetwork.prop('title', '');

                if (this.validationItemNetwork.hasClass('valid') == false)
                    this.validationItemNetwork.addClass('valid');

                this.validationItemNetwork.removeClass('not-valid');
            }
            else {
                valid = false;

                this.validationItemNetworkMessages.append($("<li/>").html(validation.message));
                //this.validationItemNetwork.prop('title', validation.message);

                if (this.validationItemNetwork.hasClass('not-valid') == false)
                    this.validationItemNetwork.addClass('not-valid');

                this.validationItemNetwork.removeClass('valid');
            }


            //*************
            //Date and Time
            //*************
            validation = this.validateDatetimeConfiguration(data.datetime);

            this.validationItemDatetimeMessages.empty();
            if (validation.valid == true) {
                this.validationItemDatetime.prop('title', '');

                if (this.validationItemDatetime.hasClass('valid') == false)
                    this.validationItemDatetime.addClass('valid');

                this.validationItemDatetime.removeClass('not-valid');
            }
            else {
                valid = false;

                this.validationItemDatetimeMessages.append($("<li/>").html(validation.message));

                if (this.validationItemDatetime.hasClass('not-valid') == false)
                    this.validationItemDatetime.addClass('not-valid');

                this.validationItemDatetime.removeClass('valid');
            }


            //*************
            //Update start btn state
            //*************
            this.startBtn
                .prop(
                    'disabled',
                    ((valid == false) || (this.processingNewConfig == true))
                )
                .prop(
                    'title',
                    (valid == false) ? 'Configuration is not valid.' : ''
                );
        },
        validateConfiguration: function (data) {
            //************
            //Network
            //************
            var networkValidation = this.validateNetworkConfiguration(data);

            if (networkValidation.valid == false)
                return networkValidation;


            //************
            //Date and Time
            //************
            var datetimeValidation = this.validateDatetimeConfiguration(data.datetime);

            if (datetimeValidation.valid == false)
                return datetimeValidation;


            return { valid: true, message: '', };
        },
        validateDatetimeConfiguration: function (data) {
            //************
            //System time
            //************
            if (!data.date)
                return { valid: false, message: 'System date must be specified.' };

            if (!data.time)
                return { valid: false, message: 'System time must be specified.' };

            if (!data.timeZoneId)
                return { valid: false, message: 'System time zone must be specified.' };

            return { valid: true, message: '', };
        },
        validateNicConfiguration: function (data) {
            if (data.dhcpEnabled == false) {
                if (!data.ip4Address)
                    return { valid: false, message: data.name + ' ip address must be specified.' };

                if (!data.subnetMask)
                    return { valid: false, message: data.name + ' subnet mask must be specified.' };

                if (!data.defaultGateway)
                    return { valid: false, message: data.name + ' default gateway must be specified.' };
            }

            if ((data.isDnsServerAutomatic == false) && (!data.preferredDns))
                return { valid: false, message: data.name + ' preferred dns must be specified.' };

            return { valid: true, message: '' };
        },
        validateNetworkConfiguration: function (data) {
            var nicWifi = data.networkWifi,
                nicEthernet = data.networkEthernet;


            //************
            //General
            //************
            if ((nicEthernet.status != 'UP') && (nicWifi.status != 'CONNECTED'))
                return { valid: false, message: 'Both networks, Ethernet and Wi-Fi, are disconnected.' };

            if ((nicEthernet.dhcpEnabled == false) && (nicWifi.dhcpEnabled == false))
                return { valid: false, message: 'Both networks, Ethernet and Wi-Fi, can not be configured with static ip simultaneously.' };

            //************
            //Ethernet
            //************
            var nicEthernetValidation = this.validateNicConfiguration(nicEthernet);

            if (nicEthernetValidation.valid == false)
                return nicEthernetValidation;

            //************
            //Wifi
            //************
            var nicWifiValidation = this.validateNicConfiguration(nicWifi);

            if (nicWifiValidation.valid == false)
                return nicWifiValidation;


            return { valid: true, message: '', };
        },

        startBtn_click: function (e) {
            try {
                var that = this,
                    allData = this.getViewsAllData();

                var validation = this.validateConfiguration(allData);

                if (validation.valid == true) {
                    $('#tz-footer-wrapper-container').hide();
                    this.showProcessingPoster();

                    var configData = this.getViewsConfigData();

                    //var prevText = $.trim(startBtn.text());

                    that.startBtn
                        .prop('disabled', true)
                        .prop('title', 'Processing new configuration...');

                    this.processingNewConfig = true;

                    this.callSystemTimeConfigurationService(
                        "SET_INIT_SYSTEM_CONFIG",
                        {
                            data: {
                                datetime: JSONEncode(configData.datetime),
                                networkEthernet: JSONEncode(configData.networkEthernet),
                                networkWifi: JSONEncode(configData.networkWifi),
                            },
                            success: function (resp) {
                                try {
                                    //startBtn
                                    //    .prop('disabled', false)
                                    //    .text(prevText);

                                    if (resp != null) {
                                        //if (resp.Success == true) {
                                        //    app.views.topMessages.showMessage(
                                        //        //that.i18n.translate('response_ok_change_apply').fetch()
                                        //        that.i18n.translate("Applying changes to configuration. This can take some minutes.").fetch()
                                        //    );
                                        //}
                                        //else {
                                        if (resp.Success == false) {
                                            that.hideProcessingPoster();

                                            that.updateValidationStatus();

                                            if (resp.Message) {
                                                app.views.topMessages.showMessage(
                                                    that.i18n.translate(resp.Message).fetch()
                                                );
                                            }
                                            else {
                                                app.views.topMessages.showMessage('Temporaly server error. Try again please.');
                                            }
                                        }
                                    }
                                    else {
                                        app.views.topMessages.showMessage(
                                            //that.i18n.translate("response_error_no_response").fetch()
                                            that.i18n.translate("No response from server.").fetch()
                                        );
                                    }
                                }
                                catch (Error) { console.error(Error); }
                            },
                            error: function (error) {
                                try {
                                    that.processingNewConfig = false;

                                    that.updateValidationStatus();
                                    //.text(prevText);

                                    app.views.topMessages.showMessage('Temporaly server error. Try again please.');
                                }
                                catch (Error) { console.error(Error); }
                            }
                        }
                    );
                }
                else {
                    app.views.topMessages.showMessage(that.i18n.translate(validation.message).fetch());
                }
            }
            catch (Error) { console.error(Error); }
        },
        //view_edited: function (view) {
        //    try
        //    {
        //        this.updateValidationStatus();
        //    }
        //    catch (Error) { console.error(Error); }
        //},
        startingPosterBtn_click: function (e) {
            try {
                this.startingPosterBtn.hide();

                this.hideStartingPoster();
            }
            catch (Error) { console.error(Error); }
        },
        view_model_change: function (model) {
            try {
                this.updateValidationStatus();
            }
            catch (Error) { console.error(Error); }
        },
        window_beforeUnload: function (e) {
            try {
                if (this.processingNewConfig == true) {
                    var msg =
                        'The system continues processing the new configuration. If this windows is closed it is possible' +
                        'that application can not be reachable until system finish to process the new settings.';

                    return msg;
                }
            }
            catch (Error) { console.error(Error); }
        },
    };


    //*****************
    //Start
    //*****************
    try {
        mainView.render();
    }
    catch (Error) { console.error(Error); }

}); 