//SCREEN-BOILERPLATE
//this boilerplate builds screens that are gonna be shown in the <div class='content'> tag of our main HTML.
//do not build app components with this boilerplate, only screens (reports)

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'),

                shiftId: null,
                shifts: [{ label: 'D', value: 1 }, { label: 'N', value: 2 }],

                crewId: null,
                crews: [{ label: 'A', value: 'A' }, { label: 'B', value: 'B' }, { label: 'C', value: 'C' }, { label: 'D', value: 'D' }],

                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: 'weights-report',
            id: 'weights-report',
            title: '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: 'HeatName', headerName: 'Heat', width: 100, pinned: 'left', cellClass: 'text-center', headerClass: 'ag-header-cell-center', cellRenderer: heatLinkRenderer },
                { field: 'ShiftId', headerName: 'Shift', width: 70, cellClass: 'text-center', headerClass: 'ag-header-cell-center' },
                { field: 'CrewId', headerName: 'Crew', width: 70, cellClass: 'text-center', headerClass: 'ag-header-cell-center' },
                { field: 'StartTap', headerName: 'Start\nTap', width: 110, fieldType: 'Datetime', format: 'MM/DD HH:mm', cellClass: 'text-center', headerClass: 'ag-header-cell-center' },
                { field: 'EndCast', headerName: 'End\nCast', width: 110, fieldType: 'Datetime', format: 'MM/DD HH:mm', cellClass: 'text-center', headerClass: 'ag-header-cell-center' },
                { headerName: 'EAF Weights', children: [
                    { field: 'SteelWeight', headerName: 'Steel', flex: 1, fieldType: 'Float', decimals: 1, cellClass: 'text-right', headerClass: 'ag-header-cell-center' },
                    { field: 'TareWeight', headerName: 'Tare', flex: 1, fieldType: 'Float', decimals: 1, cellClass: 'text-right', headerClass: 'ag-header-cell-center' },
                    { field: 'AlloyWeight', headerName: 'Alloy', flex: 1, fieldType: 'Float', decimals: 1, cellClass: 'text-right', headerClass: 'ag-header-cell-center' },
                ]},
                { headerName: 'Bucket Weights', children: [
                    { field: 'BucketScrapWeight', headerName: 'Scrap', flex: 1, fieldType: 'Float', decimals: 1, cellClass: 'text-right', headerClass: 'ag-header-cell-center' },
                    { field: 'BucketOtherWeight', headerName: 'Other', flex: 1, fieldType: 'Float', decimals: 1, cellClass: 'text-right', headerClass: 'ag-header-cell-center' },
                ]},
                { headerName: 'Caster Weights', children: [
                    { field: 'CasterInitialGrossWeight', headerName: 'Initial\nGross', flex: 1, fieldType: 'Float', decimals: 1, cellClass: 'text-right', headerClass: 'ag-header-cell-center' },
                    { field: 'CasterFinalGrossWeight', headerName: 'Final\nGross', flex: 1, fieldType: 'Float', decimals: 1, cellClass: 'text-right', headerClass: 'ag-header-cell-center' },
                    { field: 'CasterProcessedWeight', headerName: 'Processed', flex: 1, fieldType: 'Float', decimals: 1, cellClass: 'text-right', headerClass: 'ag-header-cell-center' },
                ]},
                { field: 'ProductsWeight', headerName: 'Products', flex: 1, fieldType: 'Float', decimals: 1, cellClass: 'text-right', headerClass: 'ag-header-cell-center' },
                { field: 'DrainWeight', headerName: 'Drain', flex: 1, fieldType: 'Float', decimals: 1, cellClass: 'text-right', headerClass: 'ag-header-cell-center' },
                { field: 'PourbackWeight', headerName: 'Pourback', flex: 1, fieldType: 'Float', decimals: 1, cellClass: 'text-right', headerClass: 'ag-header-cell-center' },
            ],

            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: 'weights-report',
                    screenTitle: this.title,
                    gridOptions: {
                        wrapHeaderText: true,
                        autoHeaderHeight: true,
                        onRowClicked: function (params) {
                            var heatName = params.data && params.data.HeatName;
                            if (heatName) {
                                app.router.navigate(
                                    app.router.resolveURL('eaf-heat-report', { heatName: heatName }, false),
                                    { trigger: 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.shiftId)
                    fixedParams.shiftId = (viewParams.shiftId != '-' && viewParams.shiftId != null) ? parseInt(viewParams.shiftId, 10) : null;
                if (viewParams.crewId)
                    fixedParams.crewId = (viewParams.crewId != '-' && viewParams.crewId != null) ? viewParams.crewId : 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.shiftId)
                                    fixedParams.shiftId = (viewParams.shiftId != '-' && viewParams.shiftId != null) ? parseInt(viewParams.shiftId, 10) : null;
                                if (viewParams.crewId)
                                    fixedParams.crewId = (viewParams.crewId != '-' && viewParams.crewId != null) ? viewParams.crewId : null;

                                that.model.set(fixedParams);

                                var params = that.model.toJSON();
                                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,
                    shiftId: (attrs.shiftId == "") ? null : attrs.shiftId,
                    crewId: (attrs.crewId == "") ? null : attrs.crewId,
                    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'),
                                    shiftId: (params.shiftId == null || params.shiftId == "") ? '-' : params.shiftId,
                                    crewId: (params.crewId == null || params.crewId == "") ? '-' : params.crewId,
                                }
                            ),
                            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 () {
                var that = this;
            },
            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) { }
            },
        });

        function heatLinkRenderer(params) {
            if (!params.value) return '';
            return '<span class="heat-link" style="color: #007bff; cursor: pointer; text-decoration: underline;">' + params.value + '</span>';
        }

        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: '@ShiftId', Type: 'INT', Value: params.shiftId },
                        { Name: '@CrewId', Type: 'CHAR', Value: params.crewId },
                    ];
                }
                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.GetHeatWeights',
                    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;
    });
