define([
    'app',
    'js/templates-loader',
    'moment',
    'components/ag-grid/ag-grid-module',
],
    function (app, T, moment, AgGridModule) {

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

        Screen.Models.Main = Backbone.Epoxy.Model.extend({
            defaults: {
                start: new moment().subtract(5, 'days').format('YYYY-MM-DD'),
                end: new moment().format('YYYY-MM-DD'),

                casterCode: null,
                casters: [{ label: '1', value: 1 }, { label: '2', value: 2 }],

                hasData: false,
                isLoading: false,
            },
            computeds: {
                start$: {
                    deps: ['start'],
                    get: function (value) {
                        return value;
                    },
                    set: function (value) {
                        return { start: (value) ? new moment(value, app.translate(app, 'MM/DD/YYYY')).format('YYYY-MM-DD') : value, };
                    },
                },
                end$: {
                    deps: ['end'],
                    get: function (value) {
                        return value;
                    },
                    set: function (value) {
                        return { end: (value) ? new moment(value, app.translate(app, 'MM/DD/YYYY')).format('YYYY-MM-DD') : value, };
                    },
                },
            },
        });

        Screen.Views.Main = Backbone.Epoxy.View.extend({
            template: 'sequence-weights-report',
            id: 'sequence-weights-report',
            title: 'Sequence Weights Report',
            events: function () {
                return {
                    'click #refreshBtn': this.refreshBtn_click,
                    'click .btn-export-to-excel': this.exportToExcel,
                    'click #calendarStartBtn': this.calendarStartBtn_click,
                    'click #calendarEndBtn': this.calendarEndBtn_click,
                };
            },
            bindings: 'data-bind',
            bindingSources: null,
            grids: null,
            itemsColl: null,
            subviews: null,
            viewParams: null,

            columnDefs: [
                { field: 'CastStart', headerName: 'Cast Start', pinned: 'left', fieldType: 'Datetime', format: 'MM/DD HH:mm', width: 120 },
                { field: 'CastEnd', headerName: 'Cast End', fieldType: 'Datetime', format: 'MM/DD HH:mm', flex: 1, minWidth: 110 },
                { field: 'CasterCode', headerName: 'Caster', flex: 0.6, minWidth: 70 },
                { field: 'PrimeWeight', headerName: 'Prime\nWeight', headerClass: 'header-two-lines', fieldType: 'Float', decimals: 2, flex: 1, minWidth: 90 },
                { field: 'SteelWeight', headerName: 'Steel\nWeight', headerClass: 'header-two-lines', fieldType: 'Float', decimals: 2, flex: 1, minWidth: 90 },
                { field: 'AlloyWeight', headerName: 'Alloy\nWeight', headerClass: 'header-two-lines', fieldType: 'Float', decimals: 2, flex: 1, minWidth: 90 },
                { field: 'BucketScrapWeight', headerName: 'Bucket Scrap\nWeight', headerClass: 'header-two-lines', fieldType: 'Float', decimals: 2, flex: 1.1, minWidth: 100 },
                { field: 'BucketOtherWeight', headerName: 'Bucket Other\nWeight', headerClass: 'header-two-lines', fieldType: 'Float', decimals: 2, flex: 1.1, minWidth: 100 },
                { field: 'SkullWeight', headerName: 'Skull\nWeight', headerClass: 'header-two-lines', fieldType: 'Float', decimals: 2, flex: 1, minWidth: 90 },
                { field: 'KerfLoss', headerName: 'Kerf\nLoss', headerClass: 'header-two-lines', fieldType: 'Float', decimals: 2, flex: 0.9, minWidth: 80 },
                { field: 'HeadCropWeight', headerName: 'Head Crop\nWeight', headerClass: 'header-two-lines', fieldType: 'Float', decimals: 2, flex: 1.1, minWidth: 100 },
                { field: 'TailCropWeight', headerName: 'Tail Crop\nWeight', headerClass: 'header-two-lines', fieldType: 'Float', decimals: 2, flex: 1.1, minWidth: 100 },
            ],

            initialize: function () {
                this.options.state = app.view_states.loading;
                this.options.onappend = (_.isFunction(this.options.onappend)) ? this.options.onappend : function () { };

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

                this.grids = {};
                this.itemsColl = new Screen.Collections.Items();
                this.bindingSources = {};
                this.subviews = {};

                this.agGridModule = new AgGridModule({
                    columnDefs: this.columnDefs,
                    rowData: [],
                    fileName: 'Sequence-Weights-Report',
                    screenTitle: this.title,
                    gridOptions: {
                        wrapHeaderText: true,
                        autoHeaderHeight: true,
                    }
                });

                this.bindEvents();
            },

            bindEvents: function () {
                this.listenTo(this.itemsColl, 'fetch', this.processes_ready);
            },

            _refresh: function (opt) {
                this.itemsColl.reset();

                this.model.set({
                    hasData: false,
                    isLoading: true,
                });

                if (this.agGridModule && this.agGridModule.showLoadingOverlay) {
                    this.agGridModule.showLoadingOverlay();
                }

                this.refreshProcesses(opt);
            },

            refresh: function (viewParams) {
                var fixedParams = _.extend({}, Screen.Models.Main.prototype.defaults, viewParams);

                if (viewParams.start)
                    fixedParams.start = new moment(viewParams.start, 'YYYYMMDD').format('YYYY-MM-DD');
                if (viewParams.end)
                    fixedParams.end = new moment(viewParams.end, 'YYYYMMDD').format('YYYY-MM-DD');
                if (viewParams.casterCode)
                    fixedParams.casterCode = (viewParams.casterCode != '-' && viewParams.casterCode != null) ? parseInt(viewParams.casterCode, 10) : null;

                this.model.set(fixedParams);

                this._refresh({
                    reset: true,
                    params: _.extend({}, fixedParams, {}),
                });
            },

            render: function (container, viewParams) {
                var that = this;

                this.viewParams = viewParams;

                var thatContainer = (this.options.container) ? this.options.container : container;
                this.options.container = thatContainer;

                var customPath = '/app/pages/mes/' + this.template + '/';

                T.render.call(
                    this,
                    this.template,
                    function (tmp) {
                        if (!that.options.i18n) that.options.i18n = {};

                        app.getI18NJed(
                            that,
                            that.template,
                            function (i18nJED) {
                                that.options.i18n[that.template] = i18nJED;
                                that.$el.html(tmp());
                                that.applyBindings();

                                that.$el.find('.input-date').datepicker();

                                that.agGridModule.render();
                                that.$el.find('.processes-grid-container').append(that.agGridModule.$el);

                                that.append(thatContainer, that.$el);

                                var fixedParams = _.extend({}, viewParams);

                                if (fixedParams.start)
                                    fixedParams.start = new moment(fixedParams.start, 'YYYYMMDD').format('YYYY-MM-DD');
                                if (fixedParams.end)
                                    fixedParams.end = new moment(fixedParams.end, 'YYYYMMDD').format('YYYY-MM-DD');
                                if (viewParams.casterCode)
                                    fixedParams.casterCode = (viewParams.casterCode != '-' && viewParams.casterCode != null) ? parseInt(viewParams.casterCode, 10) : null;

                                that.model.set(fixedParams);

                                var params = that.model.toJSON();
                                that.agGridModule.gridReadyPromise.then(function () {
                                    that._refresh({
                                        reset: true,
                                        params: _.extend({}, params, {}),
                                    });
                                });
                            },
                            true,
                            customPath
                        );
                    },
                    customPath
                );
            },

            processes_ready: function () {
                try {
                    var that = this;
                    setTimeout(
                        function () {
                            that.agGridModule.setRowDataAsCollection(that.itemsColl);
                            that.agGridModule.hideOverlay();
                            that.model.set({
                                hasData: (that.itemsColl.length > 0),
                                isLoading: false,
                            });
                        },
                        100
                    );
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },

            refreshProcesses: function (options) {
                var that = this,
                    attrs = this.model.toJSON(),
                    opt = _.extend({}, options, { params: {} });

                if ((opt.refresh == true) || (opt.reset == true)) {
                    this.model.set('isLoading', true);
                    this.agGridModule.showLoadingOverlay();
                }

                this.itemsColl.fetch({
                    start: attrs.start,
                    end: attrs.end,
                    casterCode: (attrs.casterCode == "") ? null : attrs.casterCode,
                    refresh: true,
                });
            },

            exportToExcel: function () {
                this.agGridModule.exportToExcel(false);
            },

            calendarStartBtn_click: function () {
                this.$el.find('#dateStartTbx').datepicker('show');
            },
            calendarEndBtn_click: function () {
                this.$el.find('#dateEndTbx').datepicker('show');
            },

            refreshBtn_click: function (e) {
                try {
                    var params = this.model.toJSON();
                    app.router.navigate(
                        app.router.resolveURL(
                            app.router.currentModule,
                            _.extend(
                                {},
                                params,
                                {
                                    start: new moment(params.start, 'YYYY-MM-DD').format('YYYYMMDD'),
                                    end: new moment(params.end, 'YYYY-MM-DD').format('YYYYMMDD'),
                                    casterCode: (params.casterCode == null || params.casterCode == "") ? '-' : params.casterCode,
                                }
                            ),
                            false
                        ),
                        { trigger: false, }
                    );

                    this._refresh({
                        reset: true,
                        params: _.extend({}, params, {}),
                    });

                    window.scrollTo(0, 0);
                }
                catch (Error) { console.error(Error.stack); }
            },

            append: function (container, el) {
                el = (el != null && el != undefined) ? el : this.$el;

                if (this.options.state == app.view_states.loading
                    || this.options.state == app.view_states.shown) {
                    this.options.state = app.view_states.shown;
                    container.append(el);
                    this.options.onappend(this);
                }

                if (this.options.state == app.view_states.hidden) {
                    container.append(el);
                }

                if (this.options.state == app.view_states.closed) {
                    return;
                }
            },
            bindViewScopedEvents: function () { },
            unbindViewScopedEvents: function () { },
            close: function () {
                this.options.state = app.view_states.closed;
                if (this.agGridModule && this.agGridModule.destroy) {
                    this.agGridModule.destroy();
                }
                this.closeSubviews();
                this.remove();
                this.unbindViewScopedEvents();
                this.unbind();
            },
            closeSubviews: function () {
                _.each(this.subviews, function (sview) {
                    sview.close();
                });
            },
            show: function () {
                this.options.state = app.view_states.shown;
                this.showSubviews();
                this.bindEvents();
                this.$el.show();
            },
            showSubviews: function () {
                _.each(this.subviews, function (sview) {
                    sview.show();
                });
            },
            hide: function () {
                this.options.state = app.view_states.hidden;
                this.hideSubviews();
                this.$el.hide();
                this.unbind();
                this.stopListening();
            },
            hideSubviews: function () {
                _.each(this.subviews, function (sview) {
                    sview.hide();
                });
            },
            preRender: function () {
                app.models.subnavbar.set("subnavbar", false);
            },
            reRender: function (viewParams) {
                try {
                    this.refresh(viewParams);
                } catch (Error) { }
            },
        });

        Screen.Collections.Items = Backbone.Collection.extend({
            isFetching: false,
            currentPage: 1,
            pageSize: 100,

            fixedParameters: [],

            fetch: function (params) {
                var that = this,
                    qp = new Core.Database.QueryParameters(),
                    options = params ? _.clone(params) : {};

                if (options.refresh) {
                    this.resetPagination(true);
                    this.fixedParameters = [
                        { Name: '@Start', Type: 'DATETIME', Value: params.start, },
                        { Name: '@End', Type: 'DATETIME', Value: params.end, },
                        { Name: '@CasterCode', Type: 'INT', Value: params.casterCode, },
                    ];
                }
                this.isFetching = true;

                _.each(this.fixedParameters, function (qpParams) {
                    qp.Add(qpParams.Name, qpParams.Type, qpParams.Value);
                });

                qp.Add('@fromRow', 'INT', 0);
                qp.Add('@rowsToFetch', 'INT', 100000);

                Core.Json.CallProcedure(
                    app.DatabaseNames.MES + '.MES.GetSequenceWeightsReport',
                    qp,
                    {
                        onSuccess: function (resp) {
                            try {
                                if ((resp) && (resp.Table)) {
                                    var newColl = resp.Table;
                                    var method = (options.refresh) ? 'set' : 'add';
                                    that[method](newColl);
                                    that.trigger('fetch', that, newColl);

                                    if (newColl.length == 0 && method == 'add')
                                        that.currentPage--;

                                    that.isFetching = false;
                                }
                                else {
                                    if ((resp) && (resp.Message)) {
                                        console.error(new Error(resp.Message).stack);
                                        app.views.topMessages.showMessage('CALL TO DATABASE FAILED', { stay: 5000, });
                                    }
                                    else {
                                        app.views.topMessages.showMessage('SERVER RESPONSE NOT VALID', { stay: 5000, });
                                        console.error(new Error('SERVER_RESPONSE_NOT_VALID').stack);
                                    }
                                    that.trigger('fetch', that, []);
                                }
                                that.isFetching = false;
                            }
                            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); that.trigger('fetch', that, []); that.isFetching = false; }
                        },
                        onFailure: function (resp) {
                            console.error(resp);
                            that.trigger('fetch', that, []);
                            that.isFetching = false;
                        },
                        Secured: true,
                        Async: true,
                    },
                    app.ConnectionStrings.app
                );
                return this;
            },
            getNextPage: function (options) {
                if (!this.isFetching) {
                    this.currentPage++;
                    options = (_.isObject(options)) ? options : {};
                    this.fetch(options);
                }
            },
            resetPagination: function (force) {
                if (!this.isFetching || force == true) {
                    this.currentPage = 1;
                } else {
                    _.delay(this.resetPagination, 100);
                }
            },
        });

        return Screen;
    });
