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

    function (app, T, Backgrid, moment, ) {

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

        Screen.Models.AssignCoverModal = Backbone.Epoxy.Model.extend({
            defaults: {
                covers: null,
                coverId: 1,
                HeatNumber: "",
                action: 'A',
            },
            initialize: function () {
                var covers = this.fetchAvailableCovers();
                this.set('covers', covers);

            },
            fetchAvailableCovers: function () {
                var covers = [];
                var qp = new Core.Database.QueryParameters();
                Core.Json.CallProcedure(
                    app.DatabaseNames.MES + '.CAS.GetAvailableCovers',
                    qp,
                    {
                        onSuccess: function (resp) {
                            try {

                                if (resp.Table) {
                                    covers = resp.Table.map(item => {
                                        return {
                                            value: item.CoverId,
                                            label: 'Cover '+item.CoverId
                                        };
                                    });
                                }
                                else {
                                    if ((resp) && (resp.Message)) {
                                        app.views.topMessages.showMessage(resp.Message, { stay: 5000, });
                                        console.error(resp.Message);
                                        that.set({
                                            hasData: false,
                                            isLoading: false,

                                        });

                                    }
                                    else {
                                        app.views.topMessages.showMessage("Server response not valid.", { stay: 5000, });
                                        console.error("Server response not valid.");
                                        that.set({
                                            hasData: false,
                                            isLoading: false,
                                        });
                                    }

                                }


                            }
                            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                        },
                        Async: false,
                        Secured: true,
                    },
                    app.ConnectionStrings.app
                );

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

                    this.fixedParameters = [
                        { Name: '@CoverId', Type: 'INT', Value: params.CoverId, },
                        { Name: '@HeatName', Type: 'VARCHAR', Value: params.HeatNumber, },
                        { Name: '@action', Type: 'VARCHAR', Value: params.action, },
                    ];
                    _.each(this.fixedParameters, function (qpParams) {
                        qp.Add(qpParams.Name, qpParams.Type, qpParams.Value);
                    });
                    Core.Json.CallProcedure(
                        app.DatabaseNames.MES + '.CAS.UpdateCoverHeat',
                        qp,
                        {
                            onSuccess: function (resp) {
                                try {
                                    if (resp && !resp.Message) {
                                        if(params.action == 'A'){
                                            app.views.topMessages.showMessage('Heat : ' + params.HeatNumber + ' assigned to Cover: ' + params.CoverId, { stay: 2000, });
                                        }
                                        else {
                                            app.views.topMessages.showMessage('Unassigned Heat: ' + params.HeatNumber + 'from Cover: ' + params.CoverId, { 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.AssignCoverModal = Backbone.Epoxy.View.extend({
            template: "modal-assign-cover",
            className: "modal hide fade",
            bindings: "data-bind",
            title: "Assing Cover To Heat",
            isCacheable: true,
            events: function () {
                return {
                    "click #acceptBtn": this.acceptBtn_click,
                    "click #cancelBtn": 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,
            disposed: false,
            isRendered: false,
            preventDispose: false,
            visible: false,
            row: [],
            grid: [],
            initialize: function (options) {
                _.extend(this, options);
                if (!this.model) {
                    this.model = new Screen.Models.AssignCoverModal();
                }

                const row = options.rowModel;

                this.bus = options.bus;

                if (options.data) {
                    var data = options.data;
                    this.model.set({
                        HeatNumber: data.HeatNumber,
                        action: data.action
                    });
                }
               
                this.parent = options.parent;
                this.bindEvents();
                var that = this;

                return this;
            },
            hide: function (preventDispose) {
                this.preventDispose = (preventDispose);

                this.$el.modal('hide');

            },
            render: function (container) {
                if (container)
                    this.container = container;

                var that = this;
                var customPath = '/app/templates/' + this.template + '/';
                T.render.call(this, this.template, function (tmp) {
                    if (!that.i18n) that.i18n = {};
                    app.getI18NJed(that, that.template, function (i18nJED) {
                        that.i18n[that.template] = i18nJED;
                        that.$el.html(tmp(that.model.toJSON()));
                        that.applyBindings();

                        that.isRendered = true;

                        that.trigger("render");
                       
                    }, true, customPath);

                }, customPath, "assign_cover");

            },
            show: function () {
                if (!this.isRendered) {

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

                return this;
            },

            bindEvents: function () {
                var that = this;
                this.listenToOnce(that, "render", that.view_render);
                this.listenTo(that.model, 'edited', () => { that.bus.trigger("modalAcceptBtn") });


            },

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

                        this.remove();
                        this.unbind();

                        this.disposed = true;
                    }
                }
            },
            preRender: function () {
            },
            reRender: function () {
            },

            acceptBtn_click: function () {
                try {
                    var that = this;
                    var params = {HeatNumber: that.model.get('HeatNumber'), CoverId: that.model.get('coverId'), action: that.model.get("action")}
                    that.model.updateCoverHeat(params)

                    this.close();

                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
            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); }
            },
            modal_shown: function (e) {
                try {
                    this.$el.find(".autofocus").focus();
                }
                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); }
            },
        });
        // Required, return the module for AMD compliance.
        return Screen;

    });