define([
    // Application.
    "app",

    //templates-loader


    'js/templates-loader',
    'modules/modal2',
    'moment',
    'modules/modal-trigger-acceptance-wrong-mo/modal-trigger-acceptance-wrong-mo',
    'modules/unk-heat-detection-modal/unk-heat-detection-modal',

    'backgrid/infinator',
    'backgrid/moment-cell',
    'js/jquery.clearsearch/jquery.clearsearch',
    'js/jstree/jstree',


],

    function (app, T, Modal, moment, LadlePositionsModal,UNKDetectionModal) {

        var NavBarLadlePositions = {
            Model: {},
            Views: {},
            NOT_DECLARED_DELAY_CODE_ID: -1,
        }

        //you can create more than one model, default model is called Model.
        NavBarLadlePositions.Model = Backbone.Model.extend({
            defaults: {


                cas1PosActive: false

                , syncEvery: 1000 * 15 // 15 sec
                , syncTimeout: null

                // MELT ORDER
                , MOsnoozeActive: false
                , MOsnoozeTimer: 0
                , MOsnoozeRefresh: 1000 * 60 * 3 // 3 min

                // UNK
                , UNKsnoozeActive: false
                , UNKsnoozeTimer: 0
                , UNKsnoozeRefresh: 1000 * 60 * 3 // 3 min
                , MustDetectUNK: false

                , modalUNK: null
                , modalMO: null

             
            }
            , initialize: function () {
                this.bindEvents();
                this.bus = _.extend({}, Backbone.Events);
            },

            bindEvents: function () {
                _.bindAll(this);
            },
            fetch: function () {               
                // Clock running
                if (this.attributes.syncTimeout) clearTimeout(this.attributes.syncTimeout);
                this.attributes.syncTimeout = setTimeout(this.fetch, this.attributes.syncEvery);


                // Snooze MO Option 
                if (this.attributes.MOsnoozeActive) {
                    this.attributes.MOsnoozeTimer += this.attributes.syncEvery;
                    if (this.attributes.MOsnoozeTimer >= this.attributes.MOsnoozeRefresh) {
                        this.attributes.MOsnoozeTimer = 0;
                        this.attributes.MOsnoozeActive = false;
                    }
                }


                // Snooze Option UNK
                if (this.attributes.UNKsnoozeActive) {
                    this.attributes.UNKsnoozeTimer += this.attributes.syncEvery;
                    if (this.attributes.UNKsnoozeTimer >= this.attributes.UNKsnoozeRefresh) {
                        this.attributes.UNKsnoozeTimer = 0;
                        this.attributes.UNKsnoozeActive = false;
                        this.attributes.MustDetectUNK = true;
                    }
                }

                var UNKAllowed = false;

                var MOAllowed  = false;

                if ($.inArray('UNKHeatDetection', app.models.user.get('roles')) == -1) {
                    UNKAllowed = false;
                } else if (this.attributes.UNKsnoozeActive === false) {
                    UNKAllowed = true;
                } else {
                    UNKAllowed = false;
                }

                if ($.inArray('WrongMODetection', app.models.user.get('roles')) == -1) {
                    MOAllowed = false;
                } else if (this.attributes.MOsnoozeActive === false) {
                    MOAllowed = true;
                } else {
                    MOAllowed = false;
                }

                if (MOAllowed || UNKAllowed) {
                    this.fetchDetection();
                }

            },

            fetchDetection: function () {
                var that = this;
                var modalData = null,
                    qp = new Core.Database.QueryParameters();

                var UNKAllowed = false;

                var MOAllowed = false;

                if ($.inArray('UNKHeatDetection', app.models.user.get('roles')) == -1) {
                    UNKAllowed = false;
                } else if (this.attributes.UNKsnoozeActive === false) {
                    UNKAllowed = true;
                } else {
                    UNKAllowed = false;
                }

                if ($.inArray('WrongMODetection', app.models.user.get('roles')) == -1) {
                    MOAllowed = false;
                } else if (this.attributes.MOsnoozeActive === false) {
                    MOAllowed = true;
                } else {
                    MOAllowed = false;
                }



                if (UNKAllowed || MOAllowed) {
                    Core.Json.CallProcedure(
                        app.DatabaseNames.MES + '.LAD.CheckPopupConditions', qp, {
                        Secured: true,
                        onSuccess: function (data) {
                            try {
                                if (data && !data.Message) {
                                    //Melt Order DETECTION
                                    if (MOAllowed) {
                                        if (data.Table.length === 0) {
                                            that.closeOpenModal("MO");
                                        }
                                        if (data.Table && data.Table[0]) {
                                            modalData = data.Table[0];
                                            if (modalData.Accepted === false) {
                                                that.showModal(modalData, "MO");
                                            }
                                        }
                                    }

                                    //UNK DETECTION
                                    if (UNKAllowed) {
                                        // EXISTS AN UNK HEAT DETECTED FROM DATABASE
                                        if (data.Table1 && data.Table1[0] && data.Table1[0].UNKDetected === 1) {
                                            if (that.get('MustDetectUNK')) {                                            // IS CORRECT TO DETECT THE UNK. THE WAITING TIME FINISHED
                                                var message = data.Table1[0].Message ? data.Table1[0].Message : ''
                                                that.showUNKModal(message);
                                                that.set({
                                                    //UNKsnoozeTimer: 0,        // If uncomment these lines the waiting time is 30 seconds. If not the waiting time is 3 minutes
                                                    //UNKsnoozeActive: false,   // If uncomment these lines the waiting time is 30 seconds. If not the waiting time is 3 minutes
                                                    MustDetectUNK: false,
                                                });
                                            } else if (!that.get('MustDetectUNK')) {                        // IS "NOT" CORRECT TO DETECT THE UNK YET. WE NEED TO WAIT 3 minutes to validate the UNK HEAT
                                                console.log("POTENTIAL UNK Heat");
                                                that.set({ UNKsnoozeActive: true });
                                            }
                                        }
                                    }
                                    return that;
                                }
                            }
                            catch (Error) {
                                console.error(Error);
                            }
                        }
                        , onFailure: function () {
                            try {
                            } catch (Error) {
                                console.error(Error);
                            }
                        }
                        , Async: true
                    }, app.ConnectionStrings.app);
                }
            },


            closeOpenModal: function (roleName) {
                if (roleName === 'MO' && this.attributes.modalMO) {
                    this.attributes.modalMO.close();
                }
            },
            showModal: function (data, roleName) {
                if (roleName === 'MO') {
                    this.showMOModal(data,roleName);
                }
            },

            showUNKModal: function (message) {
                var attrs = this.toJSON();
                var that = this;
                if ($('.modal.in').length == 0) { // Check if there is another modal of any kind displayed to prevent issues.       
                    if (that.attributes.modalUNK == null) { //Check if delays modal is not initialized yet because maybe it was initialized and it is waiting for server data to be displayed.
                        that.attributes.modalUNK = new UNKDetectionModal.Views.UNKDetectionModal({
                            parent: this,
                            message: message,
                            bus: that.bus,
                        });

                        this.listenTo(that.attributes.modalUNK, 'close', function () {
                            try {
                                that.attributes.modalUNK = null;
                            }
                            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                        });
                        try {
                            if ($('.modal.in').length == 0) { //Check again if there is another modal of any kind displayed to prevent issues.
                                that.attributes.modalUNK.show();
                            }
                            else {
                                that.attributes.modalUNK.close();
                                that.attributes.modalUNK = null;
                            }
                        }
                        catch (e) {
                            if (that.attributes.modalUNK != null) {
                                that.attributes.modalUNK.close();
                                that.attributes.modalUNK = null;
                            }
                            app.views.topMessages.showMessage(app.translate([that, app], 'MODAL_DISPLAY_ERROR'), { stay: 5 * 1000, });
                            console.error((e.stack) ? e.stack : new Error(e).stack);
                        }
                    }
                }            
            },    
            showMOModal: function (data, roleName) {
                var attrs = this.toJSON();
                var that = this;
                if ($('.modal.in').length == 0) { // Check if there is another modal of any kind displayed to prevent issues.   
                    if (that.attributes.modalMO == null) { //Check if delays modal is not initialized yet because maybe it was initialized and it is waiting for server data to be displayed.
                        that.attributes.modalMO = new LadlePositionsModal.Views.LadlePositionModal({
                            parent: this,
                            data: data,
                            roleName: roleName,
                            bus: that.bus,
                        });

                        this.listenTo(that.attributes.modalMO, 'close', function () {
                            try {
                                that.attributes.modalMO = null;
                            }
                            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                        });
                        try {
                            if ($('.modal.in').length == 0) { //Check again if there is another modal of any kind displayed to prevent issues.
                                that.attributes.modalMO.show();
                            }
                            else {
                                that.attributes.modalMO.close();
                                that.attributes.modalMO = null;
                            }
                        }
                        catch (e) {
                            if (that.attributes.modalMO != null) {
                                that.attributes.modalMO.close();
                                that.attributes.modalMO = null;
                            }
                            app.views.topMessages.showMessage(app.translate([that, app], 'MODAL_DISPLAY_ERROR'), { stay: 5 * 1000, });
                            console.error((e.stack) ? e.stack : new Error(e).stack);
                        }
                    }
                }
            },
        });

        NavBarLadlePositions.Views.Main = Backbone.Epoxy.View.extend({
            template: "navbar-ladle-positions/navbar-ladle-positions"
            , id: ""
            , title: ""
            , isCacheable: false
            , events: function () {
                return {
                };
            }
            , bindings: "data-bind"

            , initialize: function () {
                if (!this.model)
                    this.model = new NavBarLadlePositions.Model();
                //this.bus = _.extend({}, Backbone.Events);
                //this.bus.on("modalClose", this.onModalClose, this);
                this.model.bus.on("cancelBtn", this.onSnooze, this);
                this.bindEvents();

            }
            , onSnooze: function (model) {
                if (model.RoleName === 'MO') {
                    this.model.set({ MOsnoozeActive: true});
                }
            }
            , onModalClose: function () {
            }

            , bindEvents: function () {          
            }
            , render: function (container, viewParams) {
                var that = this;
                var thatContainer = container;
                T.render.call(this, this.template, function (tmp) {
                    //getInternationalizationData
                    if (!that.options.i18n) that.options.i18n = {};
                    app.getI18NJed(that, that.template, function (i18nJED) {
                        //storing internationalization data
                        that.options.i18n[that.template] = i18nJED;

                        //loading the view and appeding it to the views's $el.
                        that.$el.html(tmp(that.model.toJSON()));

                        //necessary for data-bind in aspx
                        that.applyBindings();



                    });
                });
            }
            , hide: function () {
                this.$el.hide();
            }
            , reRender: function (viewParams) {
            }
            , refresh: function (viewParams) {
            }

            , close: function () {
                this.remove();
                this.unbind();
            }
            , show: function () {
                this.$el.show();
            }

        });


        // Required, return the module for AMD compliance.
        return NavBarLadlePositions;

    });
