define([
    'app',
    'js/templates-loader',
    'backgrid',
    'moment',
    'js/multiselect/virtual-select.min',
    'js/bootstrap-input-spinner/bootstrap-input-spinner',
],

    function (app, T, Backgrid, moment) {

        var Screen = {
            Models: {}, Views: {}, Collections: {},
        };

        Screen.Models.ModalTriggerAcceptance = Backbone.Epoxy.Model.extend({
            defaults: {
                Accepted: false,
                GradeName: "",
                HeatNumber: "",
                MeltOrderNumber: null,
                SteelWeight: "",
                PourbackComments: "",
                Size:"",
                MeltOrders: [],
                hasMeltOrders: false,

                RoleName: "",
                ModalTitle: "",
                pourback: false,
                LadleId: null,

            },
            fetchMeltOrders: function (params) {
                try {
                    var that = this;
                    qp = new Core.Database.QueryParameters();
                    this.fixedParameters = [
                        { Name: '@MeltOrderNumber', Type: 'CHAR', Value: params.MeltOrderNumber, },
                    ];
                    _.each(this.fixedParameters, function (qpParams) {
                        qp.Add(qpParams.Name, qpParams.Type, qpParams.Value);
                    });
                    Core.Json.CallProcedure(
                        app.DatabaseNames.MES + '.LAD.GetPopupMeltOrders',
                        qp,
                        {
                            onSuccess: function (resp) {
                                try {
                                    if (resp && !resp.Message) {
                                        if (params.fetchSizeandGrade) {
                                            that.set({
                                                Size: resp.Table1[0].MaterialSize,
                                                GradeName: resp.Table1[0].GradeName,
                                            })
                                        } else {
                                            that.set({
                                                MeltOrders: resp.Table,
                                                hasMeltOrders: resp.Table ? true : false,
                                            })
                                        }
                                    }
                                    else {
                                        if ((resp) && (resp.Message)) {
                                            app.views.topMessages.showMessage(resp.Message, { stay: 5000, });
                                            console.error(resp.Message);
                                        }
                                        else {
                                            app.views.topMessages.showMessage("Server response not valid.", { stay: 5000, });
                                            console.error("Server response not valid.");
                                        }
                                    }
                                }
                                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                            },
                            onFailure: function (resp) {
                                console.error(resp);
                            },
                            Secured: true,
                            Async: false,
                        },
                        app.ConnectionStrings.app
                    );
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
            update: function (params) {
                try {
                    var that = this;
                    qp = new Core.Database.QueryParameters();


                    var station = params.Station === 'CASTER' ? 'C' : (params.Station === 'LMF' ? 'L' : (params.Station === 'POURBACK' ? 'P' : null));

                    this.fixedParameters = [
                        { Name: '@HeatNumber', Type: 'CHAR', Value: params.HeatNumber, },
                        { Name: '@PourbackComments', Type: 'VARCHAR', Value: params.Comments, },
                        { Name: '@SteelWeight', Type: 'FLOAT', Value: params.SteelWeight, },
                        { Name: '@MeltOrderNumber', Type: 'CHAR', Value: params.MeltOrderNumber, },
                        { Name: '@Station', Type: 'CHAR', Value: station, },
                        { Name: '@LadleId', Type: 'INT', Value: parseInt(params.LadleId), },
                    ];
                    _.each(this.fixedParameters, function (qpParams) {
                        qp.Add(qpParams.Name, qpParams.Type, qpParams.Value);
                    });
                    Core.Json.CallProcedure(
                        app.DatabaseNames.MES + '.LAD.AcceptHeat',
                        qp,
                        {
                            onSuccess: function (resp) {
                                try {
                                    if (resp && !resp.Message) {
                                        if (station === 'P') {
                                            app.views.topMessages.showMessage('Pourback Heat Accepted', { stay: 2000, });
                                            that.set({ Accepted: 'true' });
                                        }
                                        else {
                                            app.views.topMessages.showMessage('Heat Accepted', { stay: 2000, });
                                        } 
                                       
                                    }
                                    else {
                                        if ((resp) && (resp.Message)) {
                                            app.views.topMessages.showMessage(resp.Message, { stay: 5000, });
                                            console.error(resp.Message);
                                        }
                                        else {
                                            app.views.topMessages.showMessage("Server response not valid.", { stay: 5000, });
                                            console.error("Server response not valid.");
                                        }
                                    }
                                }
                                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                            },
                            onFailure: function (resp) {
                                console.error(resp);
                            },
                            Secured: true,
                            Async: false,
                        },
                        app.ConnectionStrings.app
                    );
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            }
        });

        Screen.Views.ModalTriggerAcceptance = Backbone.Epoxy.View.extend({
            template: "modal-trigger-acceptance-caster-lmf",
            id: "modal-trigger-acceptance-caster-lmf",
            className: "modal modal-trigger-acceptance-caster-lmf hide fade",
            //default not cacheable, change this if you want the view to be cacheable
            // if the view is set as cacheable should also have a refresh method to reset the view without erasing the DOM.
            bindings: "data-bind",
            isCacheable: true,
            events: function () {
                return {
                    "click #acceptBtn": this.acceptBtn_click,
                    "click #cancelBtn": this.cancelBtn_click,
                    "click #dismissBtn": this.cancelBtn_click,
                    "submit form": this.form_submit,
                    "show.bs.modal": this.modal_show,
                    "shown.bs.modal": this.modal_shown,
                    "hidden.bs.modal": this.modal_hidden,
                };
            },

            container: null,
            content: null,
            disposed: false,
            isRendered: false,
            parent: null,
            preventDispose: false,
            visible: false,          
            bus: null,
            isManual: false,

            initialize: function (options) {
                _.extend(this, options);

                if (!this.model)
                    this.model = new Screen.Models.ModalTriggerAcceptance();

                this.model.set({ pourback: false });

                if (options.data) {
                    var data = options.data;
                    this.model.set({
                        Accepted: data.Accepted,
                        GradeName: data.GradeName,
                        HeatNumber: data.HeatNumber,
                        MeltOrderNumber: data.MeltOrderNumber,
                        SteelWeight: data.SteelWeight,
                        Size: data.MaterialSize,
                        ModalTitle: options.roleName === 'POURBACK'
                            ? `Confirm Pourback Location - Heat: ${data.HeatNumber}`
                            : (options.roleName + ' -  Heat: ' + data.HeatNumber + ' | Ladle: ' + data.LadleID),
                        LadleId : data.LadleID,
                    });
                }
              
                if (options.roleName) {
                    this.model.set({
                        RoleName: options.roleName,
                        pourback: options.roleName === 'POURBACK' ? true : false
                    })
                }
                if (options.roleName !== 'POURBACK') {
                    this.model.fetchMeltOrders({
                        MeltOrderNumber: data.MeltOrderNumber,
                    });
                }

                this.bus = options.bus;

                this.bindEvents();


                return this;
            },


            bindEvents: function () {
                this.listenToOnce(this, "render", this.view_render);

                _.bindAll(this, 'on_keypress'),
                    $(document).bind('keydown', this.on_keypress);
                this.listenTo(this.model, 'change:MeltOrderNumber', this.meltOrderNumber_changed);
            },
            meltOrderNumber_changed: function () {
                var attrs = this.model.toJSON()
                if (attrs.RoleName !== 'POURBACK')
                    this.model.fetchMeltOrders({ MeltOrderNumber: attrs.MeltOrderNumber, fetchSizeandGrade: true });
            },
            render: function (container) {
                if (container)
                    this.container = container;

                //the screens have a custompath, so it has to be specified in the customPath variable that is
                //then sent to the template loader.
                var that = this,
                    customPath = "/app/templates/modal-trigger-acceptance-caster-lmf/";

                var attrs = this.model.toJSON();

                T.render.call(this, this.template, function (tmp) {
                    if (!that.i18n) that.i18n = {};
                    app.getI18NJed(that, that.template, function (i18nJED) {
                        //storing internationalization data
                        that.i18n[that.template] = i18nJED;
                        //loading the view and appeding it to the views's $el.
                        that.$el.html(tmp(that.model.toJSON()));
                        that.applyBindings();

                        that.isRendered = true;

                        that.trigger("render");


                    }, true, customPath);

                }, customPath, "modal_trigger_acceptance_caster_lmf");
            },


            setData: function (attrs) {
                this.model.set(attrs);
            },
           
            show: function () {
                if (!this.isRendered) {
                    this.render();
                }
                else {
                    if (this.model.get('manual') == false) {
                        this.$el.modal({
                            keyboard: false,
                            backdrop: 'static',
                        });

                    }
                    else {
                        this.$el.modal({
                            keyboard: true,
                            backdrop: 'both',
                        });
                    }
                }

                return this;
            },
            acceptBtn_click: function (e) {
                var that = this;
                try {
                    var attrs = this.model.toJSON();
                    this.model.update({
                        HeatNumber: attrs.HeatNumber,
                        SteelWeight: attrs.SteelWeight,
                        Comments: attrs.PourbackComments,
                        MeltOrderNumber: attrs.MeltOrderNumber,
                        Station: attrs.RoleName === 'CASTER' ? 'CASTER' : (attrs.RoleName === 'LMF' ? 'LMF' : 'POURBACK'),
                        LadleId: attrs.LadleId
                    })
                    
                    this.close()
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },


            on_keypress: function (e) {          
                try {
                    if (e.which === 27) {
                        this.close();
                    }

                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
            cancelBtn_click: function () {
               // this.bus.trigger("cancelBtn", this.model.toJSON());

                this.close()
            },
            close: function () {
                if (this.disposed == false) {
                    if (this.visible == true) {
                        this.hide();
                    }
                    else {
                        this.trigger('close');
                        this.remove();
                        this.unbind();

                        this.disposed = true;
                    }
                }
                if (this.bus) {
                    this.bus.trigger("modalClose");
                }
            },
            hide: function (preventDispose) {
                this.preventDispose = (preventDispose);
                this.$el.modal('hide');
            },
            
            form_submit: function (e) {
                try {
                    e.preventDefault();
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },

            modal_hidden: function (e) {
                try {
                    this.visible = false;
                    if (!this.preventDispose)
                        this.close();
                    else
                        this.preventDispose = false;
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
            modal_show: function (e) {
                try {
                    this.visible = true;
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },

            renderSearchDropDown: function () {
                var that = this;

                var vsm = new VirtualSelect.init({
                    ele: '#meltOrders',
                    options: that.model.get('MeltOrders'),
                    multiple: false,
                    search: true,
                    placeholder: 'Select options here',
                    showSelectedOptionsFirst: true,
                    hideClearButton: true,
                });
                var MeltOrder = this.model.get('MeltOrderNumber');
                if (MeltOrder) document.querySelector('#meltOrders').setValue(MeltOrder);

                document.querySelector('#meltOrders').addEventListener('change', function () {
                    var newMeltOrderNumber = this.value;
                    that.model.set({
                        MeltOrderNumber: newMeltOrderNumber,
                    });
                });

            },

            modal_shown: function (e) {
                try {
                    this.$el.find(".autofocus").focus();
                    this.renderSearchDropDown();           
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
     
            view_render: function () {
                try {
                    this.show();
                  

                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
            preRender: function () {
                app.models.subnavbar.set("dateControl", false);
            },
            reRender: function () {
            },
        });


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

    });