//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([
  // Application variable, always include it to have access to app methods.
  'app',

  //templates-loader: this loads templates async.
  'js/templates-loader',
  'backgrid',
  'moment',

  'modules/elt/equipment-status',
  'modules/elt/equipment-history',

  'backgrid/computed-cell',
    "js/backgrid-0.3.5/extensions/duration-cell/backgrid-duration-cell",
  'backgrid/infinator',
  'backgrid/moment-cell',
  'js/backgrid-0.3.5/extensions/valid-limit-cell/backgrid-valid-limit-cell',
  'js/typeahead.extended/typeahead.extended'
],
function (app, T, Backgrid, moment, StatusModel, EquipmentHistory) {

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

    Screen.Models.Main = Backbone.Epoxy.Model.extend({
        defaults: {
            equipmentTypeId: 0,
            equipmentTypes: [],
            equipmentStatusCode: null,
            equipmentsStatus: [],

            ihId: app.models.ihDataSources.get('id'),

            //includeChildrens: false,

            start: new moment().subtract(1, 'days').format('YYYY-MM-DD'),
            end: new moment().format('YYYY-MM-DD'),
            equipmentName: null,
            
            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, };
                },
            },

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

            //SET THIS TO 0 TO NOT RETURN INTERNALS TYPES
            qp.Add('@includeInternals', 'BIT', 0);
            qp.Add('@ihId', 'INT', this.get('ihId'));

            Core.Json.CallProcedure(
                app.DatabaseNames.System + ".EQUIP.GetEquipmentTypes",
                qp,
                {
                    onSuccess: function (resp) {
                        try {
                            if ((resp) && (resp.Table)) {
                                var records = resp.Table;

                                var newItems = _.map(records, function (obj) {
                                    return { value: obj.Id, label: obj.Name, };
                                });

                                that.set("equipmentTypes", newItems);
                            }
                            else {
                                if ((resp) && (resp.Message))
                                    console.error(resp.Message);
                                else
                                    console.error("Server response not valid.");
                            }
                        }
                        catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                    },
                    onFailure: function (resp) {
                        console.error(resp);
                    },
                    Secured: true,
                    Async: false,
                },
                app.ConnectionStrings.app
            );

            return this;
        },
        fetchEquipments: function (options) {
            var that = this,
                qp = null;

            var opt = _.extend(
                { error: function () { }, success: function () { }, },
                options
            );

            if (opt.params) {
                //Check if params is a query parameters instance or not.
                if (opt.params.GetQueryParameter) {
                    qp = opt.params;
                }
                else {
                    qp = new QueryParameters();

                    for (var pname in opt.params)
                        qp.Add(pname, 'VARCHAR', opt.params[pname]);
                }
            }

            qp.Add('@isCatalog', 'BIT', 1);
            qp.Add('@ihId', 'INT', this.get('ihId'));

            Core.Json.CallProcedure(
                app.DatabaseNames.System + ".EQUIP.GetEquipments",
                qp,
                {
                    onSuccess: function (resp) {
                        try {
                            if ((resp) && (resp.Table)) {
                                var records = resp.Table;
                                opt.success(records);
                            }
                            else {
                                if ((resp) && (resp.Message))
                                    console.error(resp.Message);
                                else
                                    console.error("Server response not valid.");
                            }
                        }
                        catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                    },
                        
                    onFailure: function (resp) {
                        console.error(resp);
                    },
                    Secured: true,
                    Async: false,
                },
                app.ConnectionStrings.app
            );

            return this;
        },
    });

    Screen.Views.Main = Backbone.Epoxy.View.extend({
        template: 'equipments-history',
        id: 'equipments-history',
        title: 'Equipments History',
        events: function () {
            return {
                'click #refreshBtn': this.refreshBtn_click,
                'keypress #searchTbx': this.searchTbx_keypress,
                'click #showSearchItemsBtn': this.showSearchItemsBtn_click,
            };
        },
        bindings: 'data-bind',
        bindingSources: null,
        items:null,
        subviews: null,
        viewParams: null,
        searchTbx: null,
        searchItems: null,

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

            var that = this;

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

            this.model.fetchEquipmentTypes();


            this.items = new Screen.Collections.Items();

            

            this.bindingSources = {};

            this.subviews = {
            };


            this.autoRefresh = {
                enabled: null
                , toid: null
                , every: 5 * 1000
            };

            this.bindEvents();
        },
        bindEvents: function () {
            //this function should be in every view that uses listenTo anywhere
            //all the model bindings or view-model binding should be here, to manage
            //the show/hide view easily
            this.listenTo(this.model, "change:equipmentTypeId", this.model_change_equipmentTypeId);
        },
        _refresh: function (opt) {
            //console.log('autorefresh: ' + new Date().toString()); 
            if (this.autoRefresh.toid !== null) {
                clearTimeout(this.autoRefresh.toid);
                this.autoRefresh.toid = null;
            }

            this.refreshHistory(opt);

            if (this.autoRefresh.enabled == true) {
                var that = this 

                this.autoRefresh.toid = setTimeout(
                    function () { that._refresh(); },
                    this.autoRefresh.every
                );
            }
        },
        refresh: function (viewParams) {
            console.log('refresh excecuted');
            var fixedParams = _.extend({}, viewParams);

            if (viewParams.start)
                fixedParams.start = new moment(fixedParams.start, 'YYYYMMDD').format('YYYY-MM-DD');
            if (viewParams.end)
                fixedParams.end = new moment(fixedParams.end, 'YYYYMMDD').format('YYYY-MM-DD');
            if (viewParams.equipmentTypeId)
                fixedParams.equipmentTypeId = (viewParams.equipmentTypeId != 0) ? parseInt(viewParams.equipmentTypeId, 10) : 0;
            if (viewParams.equipmentName) {
                fixedParams.equipmentName = (viewParams.equipmentName == '-') ? null : viewParams.equipmentName;
            }
            if (viewParams.equipmentStatusCode) {
                fixedParams.equipmentStatusCode = (viewParams.equipmentStatusCode == 0) ? null : viewParams.equipmentStatusCode;
            }
            //if (viewParams.includeChildrens)
            //    fixedParams.includeChildrens = (viewParams.includeChildrens == "TRUE") ? true : false;

            this.model.set(fixedParams,  { from: 'render' });
            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;

            //the screens have a custompath, so it has to be specified in the customPath variable that is
            //then sent to the template loader.
            var customPath = '/app/custom-screens/modules/elt/' + this.template + '/';

            StatusModel.Collections.StatusCollection.fetch({
                async: false,
                params: {
                    ihId: that.model.get('ihId'),
                },
                success: function (records) {
                    try {
                        that.model.set(
                            'equipmentsStatus',
                            _.map(records, function (obj) {
                                return { value: obj.code, label: app.translate([app, that], obj.code + '_label'), };
                            })
                        );

                    }
                    catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                },
            });

            

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

                    app.getI18NJed(
                        that,
                        that.template,
                        function (i18nJED) {
                            //storing internationalization data
                            that.options.i18n[that.template] = i18nJED;

                            //loading the view and appeding it to the views's $el.
                            that.$el.html(tmp());

                            that.applyBindings();

                            //start: the view was already loaded an is on a div element, but not appended to the main container
                            //here you can perform anything you want DOM related, by getting the dom element via that.$el.find('#id')
                            //or this.$('#id')

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

                            that.searchTbx = that.$el.find("#searchTbx").typeaheadExtended({
                                items: Infinity,
                                minLength: 0,
                                source: _.bind(that.getSearchControlSource, that),
                                updater: function (item) {
                                    var match;
                                    try {
                                        match = that.selectItemFromSearchComboItem(item);
                                    }
                                    catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                                    finally {
                                        if (match)
                                            return match.Name;
                                        else
                                            return item;
                                    }
                                }
                            });
                            
                            var grid = new Backgrid.Grid({
                                className: 'backgrid table table-hover table-condensed',
                                columns: [
                                    {
                                        name: 'date',
                                        label: app.translate([that, app], 'date_label'),
                                        cell: Backgrid.Extension.MomentCell.extend({
                                            className: 'momment-cell align-center-cell',
                                            modelFormat: 'YYYY-MM-DD HH:mm:ss.SSS',
                                            displayFormat: app.translate([that, app], 'MM/DD/YYYY') + ' HH:mm',
                                        }),
                                        editable: false,
                                        sortable: false,
                                    },
                                    
                                    {
                                        name: 'equipment',
                                        label: app.translate([that, app], 'equipment_label'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell',
                                        }),
                                        editable: false,
                                        sortable: false,
                                    },
                                    {
                                        name: 'equipmentTypeName',
                                        label: app.translate([that, app], 'equipment_type_label'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell',
                                        }),
                                        editable: false,
                                        sortable: false,
                                    },
                                    {
                                        name: 'event',
                                        label: app.translate([that, app], 'event_label'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell',
                                        }),
                                        editable: false,
                                        sortable: false,
                                    },
                                    {
                                        name: 'prevStatus',
                                        label: app.translate([that, app], 'previous_status_label'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell',
                                        }),
                                        editable: false,
                                        sortable: false,
                                    },
                                    {
                                        name: 'curStatus',
                                        label: app.translate([that, app], 'current_status_label'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell',
                                        }),
                                        editable: false,
                                        sortable: false,
                                    },
                                    {
                                        name: 'comments',
                                        label: app.translate([that, app], 'comment_label'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell',
                                        }),
                                        editable: false,
                                        sortable: false,
                                    },
                                    {
                                        name: 'user',
                                        label: app.translate([that, app], 'user_label'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell',
                                        }),
                                        editable: false,
                                        sortable: false,
                                    },
                                ],
                                collection: that.items,
                                footer: Backgrid.Extension.Infinator.extend({
                                    scrollToTop: false,
                                }),
                                row: Backgrid.Row.extend({
                                    events: function () {
                                        return {
                                            'click': this.click,
                                        };
                                    },
                                    click: function (e) {
                                        try {
                                            this.model.trigger('backgrid:rowclick', this.model);
                                        }
                                        catch (Error) { console.error(Error.stack); }
                                    }
                                })
                            });
                            that.$el.find('.equipments-history-grid-container').append(grid.render().el);


                            //appending view to the main container
                            that.append(thatContainer, that.$el);


                            //Set model with view params here to prevent changes on the model when the view bindings are applied.
                            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 (fixedParams.equipmentTypeId)
                                fixedParams.equipmentTypeId = (fixedParams.equipmentTypeId != 0) ? parseInt(fixedParams.equipmentTypeId, 10) : 0;
                            if (fixedParams.equipmentName)
                                fixedParams.equipmentName = (fixedParams.equipmentName == '-') ? null : fixedParams.equipmentName;
                            if (fixedParams.equipmentStatusCode)
                                fixedParams.equipmentStatusCode = (fixedParams.equipmentStatusCode == 0) ? null : fixedParams.equipmentStatusCode;
                            //if (fixedParams.includeChildrens)
                            //    fixedParams.includeChildrens = (fixedParams.includeChildrens == "TRUE") ? true : false;

                            that.model.set(fixedParams, {from: 'render'});


                            //Call first refresh.
                            var params = that.model.toJSON();

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

                            });

                            //that.startAutoRefresh();
                        },
                        true,
                        customPath
                    );
                },
                customPath
            );
        },
        getSearchControlSource: function (query, process) {
            var that = this,
                opt = { params: {}, };


            if (query)
                opt.params.search = query;


            that.model.fetchEquipments(_.extend(
                opt,
                {
                    success: function (records) {
                        try {
                            that.searchItems = {};

                            if (records) {
                                var items = [];


                                _.each(records, function (obj) {
                                    var find = _.findWhere(items, obj.Name);
                                        
                                    if (!find) {
                                        if (obj.TypeId == that.model.get('equipmentTypeId') || that.model.get('equipmentTypeId') == 0) {
                                            var legend = obj.Name;
                                            that.searchItems[legend] = obj;
                                            items.push(legend);
                                        }
                                    }
                                });
                            }

                            process(items);
                        }
                        catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                    },
                }
            ));
            
        },
        selectItemFromSearchComboItem: function (value) {
            var item = this.searchItems[value];

            if (item) {
                this.model.set('equipmentName', value);
            } else {
                this.model.set('equipmentName', value);
            }
            return item;
        },

        model_change_equipmentTypeId: function (model, value, opt) {
            try {
                if (!opt)
                    opt = {};

                if (opt.from != 'render') {
                    this.model.set({ equipmentName: null});
                }

            } catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
        },
        searchTbx_keypress: function (e) {
            try {
                var keyCode = e.which || e.keyCode;

                if (keyCode == 13) {
                    var search = this.model.get('equipmentName');

                    if (search) {
                        var item = this.selectItemFromSearchComboItem(search);

                        if (!item) {
                            item = _.findWhere(this.searchItems, { Name: search, });

                            if (item) {

                                this.model.set('equipmentName', search);
                            }
                            else {
                                this.model.set('equipmentName', search);
                            }
                        } 
                    }
                }
            }
            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
        },
        showSearchItemsBtn_click: function (e) {
            try {
                if ((this.searchItems) && (this.searchItems.length > 0))
                    this.searchTbx.typeaheadExtended('show');
                else
                    this.searchTbx.typeaheadExtended('lookup');
            }
            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
        },
        itemsChanged: function (a, b, c) {
            var fromFetch = (
                (c && c.from && c.from == "fetch") ||
                (!c && b && b.from == "fetch")
            ) ? true : false;

            if (fromFetch) {
                this._refresh({reset: true});
            }
        },
        refreshHistory: function (options) {
            var attrs = this.model.toJSON();
            opt = _.extend({}, options, { params: {}, });
            
            if ((opt.refresh == true) || (opt.reset == true))
                this.model.set('isLoading', true);

            this.items.fetch(_.extend(opt, {
                params: {
                    ihId: attrs.ihId,
                    equipmentTypeId: (attrs.equipmentTypeId != 0) ? attrs.equipmentTypeId : null,
                    equipmentName: (attrs.equipmentName == null || attrs.equipmentName == '') ? null : attrs.equipmentName,
                    equipmentStatusCode: (attrs.equipmentStatusCode == "" || attrs.equipmentStatusCode == null) ? null : attrs.equipmentStatusCode,
                    start: attrs.start,
                    end: new moment(attrs.end, 'YYYY-MM-DD').add(1, 'days').format('YYYY-MM-DD'),
                    //includeChildrens: (attrs.includeChildrens == true) ? 1 : 0,
                },
            }));
        },
        refreshBtn_click: function (e) {
            try {
                var params = this.model.toJSON();

                app.router.navigate(
                    app.router.resolveURL(
                        app.router.currentModule,
                        _.extend(
                            {},
                            params,
                            {
                                //includeChildrens: (params.includeChildrens == true) ? "TRUE" : "FALSE",
                                start: new moment(params.start, 'YYYY-MM-DD').format('YYYYMMDD'),
                                end: new moment(params.end, 'YYYY-MM-DD').format('YYYYMMDD'),
                                equipmentTypeId: (params.equipmentTypeId != 0) ? params.equipmentTypeId : 0,
                                equipmentName: (params.equipmentName == null || params.equipmentName == '') ? '-' : params.equipmentName,
                                equipmentStatusCode: (params.equipmentStatusCode == "" || params.equipmentStatusCode == null) ? 0 : params.equipmentStatusCode
                            }
                        ),
                        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) {
                //appending view to the main container and set state to shown

                this.options.state = app.view_states.shown;
                container.append(el);

                this.options.onappend(this);
            }

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

            if (this.options.state == app.view_states.closed) {
                //return without appending.
                return;
            }
        },
        bindViewScopedEvents: function () {
            var that = this;
        },
        unbindViewScopedEvents: function () {

        },
        close: function () {
            this.options.state = app.view_states.closed;

            this.stopAutoRefresh();

            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) { }
        },
        startAutoRefresh: function () {
            try {
                if (this.autoRefresh.enabled !== true) {
                    var that = this;

                    if (this.autoRefresh.toid != null) {
                        clearTimeout(this.autoRefresh.toid);
                        this.autoRefresh.toid = null;
                    }

                    this.autoRefresh.enabled = true;

                    //use a timeout to execute the first refresh to return the handle to the start function caller.
                    //So when the caller finish it will do the first refresh.
                    this.autoRefresh.toid = setTimeout(
                        function () { that._refresh(); },
                        1
                    );
                }
            } catch (Error) { console.error(Error.stack); }
        },
        stopAutoRefresh: function () {
            if (this.autoRefresh.toid != null) {
                clearTimeout(this.autoRefresh.toid);
                this.autoRefresh.toid = null;
            }
            this.autoRefresh.enabled = false;
        },
    });

    Screen.Models.Item = EquipmentHistory.Models.EquipmentHistory;

    Screen.Collections.Items = EquipmentHistory.Collections.EquipmentsHistory.extend({
        model: EquipmentHistory.Models.EquipmentHistory, 
        pageSize: 50,
    });

    // Required, return the module for AMD compliance.
    return Screen;
});