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.LadlePositionModal = Backbone.Epoxy.Model.extend({
            defaults: {
                Accepted: false,
                GradeName: "",
                HeatNumber: "",
                MeltOrderNumber: null,
                SteelWeight: "",
                Size: "",
                MeltOrders: [],
                hasMeltOrders: false,

                RoleName: "",
                ModalTitle: "",

            },
            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 === 'MO' ? 'M' : null
                    this.fixedParameters = [
                        { Name: '@HeatNumber', Type: 'CHAR', Value: params.HeatNumber, },
                        { Name: '@SteelWeight', Type: 'FLOAT', Value: params.SteelWeight, },
                        { Name: '@MeltOrderNumber', Type: 'CHAR', Value: params.MeltOrderNumber, },
                        { Name: '@Station', Type: 'CHAR', Value: station, },
                    ];
                    _.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) {
                                        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.LadlePositionModal = Backbone.Epoxy.View.extend({
            template: "modal-trigger-acceptance-wrong-mo",
            id: "modal-trigger-acceptance-wrong-mo",
            className: "modal modal-trigger-acceptance-wrong-mo 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,
                    "keypress": this.modal_keypress,
                    "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.LadlePositionModal();

                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 === 'MO' ? ('Wrong Melt Order' + ' -  Heat: ' + data.HeatNumber + ' | Ladle: ' + data.LadleID) : (' -  Heat: ' + data.HeatNumber + ' | Ladle: ' + data.LadleID),
                    });
                }
                if (options.roleName) {
                    this.model.set({
                        RoleName: options.roleName,
                    })
                }

                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()
                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-wrong-mo/";

                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_wrong_mo");
            },
           


            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) {
                try {
                    var attrs = this.model.toJSON();
                    this.model.update({
                        HeatNumber: attrs.HeatNumber,
                        SteelWeight: attrs.SteelWeight,
                        MeltOrderNumber: attrs.MeltOrderNumber,
                        Station: attrs.RoleName === 'MO' ? 'MO' : null,
                    })

                    this.close()
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
            modal_keypress: function (e) {
                try {
                    var attrs = this.model.toJSON();
                    if (e.which == 13) {
                    }
                   
                }
                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());
            },
            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;

    });