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: "",
                L2Code: "",
                LadleID: "",
                LadlePositionID: "",
                MeltOrderNumber: null,
                PositionName: "",
                SteelWeight: "",

                MeltOrders: [],
                hasMeltOrders: false,

                RoleName: "",
                ModalTitle: "",

            },
            update: function (params) {
                try {
                    var that = this;
                    qp = new Core.Database.QueryParameters();

                    var station = params.Station === 'CASTER' ? 'C' : (params.Station === 'LMF' ? 'L' : 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 + '.MES.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: "ladle-positions-modal",
            id: "ladle-positions-modal",
            className: "modal modal-ladle-positions 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,
                        L2Code: data.L2Code,
                        LadleID: data.LadleID,
                        LadlePositionID: data.LadlePositionID,
                        MeltOrderNumber: data.MeltOrderNumber,
                        PositionName: data.PositionName,
                        SteelWeight: data.SteelWeight,
                        Size: data.MaterialSize,
                        ModalTitle: options.roleName + ' -  Heat: ' + data.HeatNumber +  ' | Ladle: '+ data.LadleID,
                    });
                }
                if (options.meltOrders) {
                    this.model.set({
                        MeltOrders: options.meltOrders,
                        hasMeltOrders: options.meltOrders ? true : false,
                    })
                }
                if (options.roleName) {
                    this.model.set({
                        RoleName: options.roleName,
                    })
                }
                this.bus = options.bus;

                this.bindEvents();

                return this;
            },

           
            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/custom-screens/rolling-mill-setup/";
                    customPath = "/app/templates/ladle-positions-modal/";

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

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


            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 === 'CASTER' ? 'CASTER' : (attrs.RoleName === 'LMF' ? 'LMF' : 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); }
            },
            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;

    });