﻿/**
@class Administration dialog box for Layer Information
@constructor
*/
TNRIS.TxHisCentralFilterWindow = function(config) {
    Ext.apply(this, config);

    this.filterParameters = [];
    this.filterStartDt = null;
    this.filterEndDt = null;
    this.refreshLayerActivity = false;

    this.mapPanel.on({
        'map-change': { scope: this, fn: this.layerChange }
    });

    this.odmLayers = new Ext.util.MixedCollection();

    var paramRecord = Ext.data.Record.create([
        { name: 'id' }
    ]);

    var paramReader = new Ext.data.ArrayReader({
        id: 0
    }, paramRecord);

    var paramProxy = new TNRIS.FunctionProxy({ findAll: 'findHisCentralParams' });

    this.paramStore = new Ext.data.Store({
        id: 'paramStore',
        proxy: paramProxy,
        reader: paramReader,
        autoLoad: true,
        listeners: {
            'load': {
                scope: this,
                fn: function(store, options) {
                    if (store.getCount() > 0) {
                        var startDate = store.getAt(0).get('ODMMinDate');

                        var st = new Date(startDate);
                        this.filterStartDt = st.format('d');
                        Ext.getCmp('dfStartDt').setValue(st.format('d'));

                        var dt = new Date();
                        this.filterEndDt = dt.format('d');
                        Ext.getCmp('dfEndDt').setValue(dt.format('d'));
                    }
                }
            }
        }
    });

    paramProxy.store = this.paramStore;

    var sm = new Ext.grid.CheckboxSelectionModel();

    sm.on({
        'selectionchange': { scope: this, fn: this.onParamSelectionChange }
    });

    this.parameterGrid = new Ext.grid.GridPanel({
        id: 'parameterList',
        title: 'TWDB Parameters',
        sm: sm,
        height: 155,
        layout: 'fit',
        loadMask: { msg: 'Loading parameters...' },
        store: this.paramStore,
        columns: [
            sm,
            {
                id: 'ODMParams',
                header: 'Parameter',
                dataindex: 'ODMParams',
                width: 210
            }
        ],
        listeners: {
            'render': function(grid) {
                grid.getSelectionModel().selectAll();
                this.refreshLayerActivity = true;
            },
            scope: this
        }
    });

    TNRIS.TxHisCentralFilterWindow.superclass.constructor.call(this, {
        title: 'TX HIS Central Export Filter',
        id: 'txHisCentralFilterWindow',
        width: 250,
        height: 275,
        resizable: false,
        stateful: false,
        plain: true,
        closable: false,
        modal: false,
        closeAction: 'hide',
        bodyStyle: 'padding:2px; background-color: transparent',
        items: [
            this.parameterGrid,
            {
                xtype: 'form',
                bodyStyle: 'padding:10px; background-color: transparent',
                items: [
                    {
                        id: 'dfStartDt',
                        xtype: 'datefield',
                        fieldLabel: 'Start Date',
                        listeners: {
                            'change': function(dateField, newValue, oldValue) {
                                if ("" == newValue) {
                                    dateField.setValue(oldValue);
                                    newValue = oldValue;
                                }
                                this.filterStartDt = newValue.format('d');
                                this.refreshLayers();
                            },
                            scope: this
                        }
                    },
                    {
                        id: 'dfEndDt',
                        xtype: 'datefield',
                        fieldLabel: 'End Date',
                        listeners: {
                            'change': function(dateField, newValue, oldValue) {
                                this.filterEndDt = newValue.format('d');
                                this.refreshLayers();
                            },
                            scope: this
                        }
                    },
                    {
                        xtype: 'button',
                        id: 'exportDataBtn',
                        text: 'Export To CSV',
                        handler: function() {
                            if (this.filterParameters.length > 0 ) {
                                window.open('./hiscentraldownload/' + "data" + '.' + "csv" + "?l=" + this.getOdmLayerIds() + "&e=" + this.getMapEnvelope() + "&p=" + this.filterParameters + "&st=" + this.filterStartDt + "&ed=" + this.filterEndDt);
                            } else {
                                Ext.Msg.alert("Problem","Please select at least one parameter to export the data");
                            }
                        },
                        scope: this
                    }
                ]
            }
        ]
    });
    this.doLayout();
};

Ext.extend(TNRIS.TxHisCentralFilterWindow, Ext.Window,
/** @scope TNRIS.LayerWindow */
    {
    layerChange: function(args) {
        if (args.add && args.add.config.source_type == 'hiscentral') {
            this.odmLayers.add(args.add._mapId, args.add);
        }

        if (args.remove) {
            this.odmLayers.removeKey(args.remove);
        }

        if (this.odmLayers.getCount() > 0 ) {
            this.showWindow();
        } else {
            this.hide();
        }
    },

    showWindow: function() {
        this.show();
        this.setPosition(15, 80);
    },

    onParamSelectionChange: function(sm) {
        if (null == this.refreshTask) {
            this.refreshTask = new Ext.util.DelayedTask();
        }
        
        this.refreshTask.delay(
            500,
            function() {
                this.filterParameters = []; 
                sm.each(function(record) {
                    this.filterParameters.push(record.get('ODMParams'));
                }, this);
                this.refreshLayers();
            },
        this);
    },

    refreshLayers: function() {
        if (this.refreshLayerActivity) {
            this.odmLayers.each(function(layer){
                layer.refreshLayerData();
            },this);
        }
    },

    getOdmLayerIds: function() {
        var odmLayerIds = [];
        this.odmLayers.each(function(layer) {
            odmLayerIds.push(layer.layerId());
        }, this);
        return odmLayerIds;
    },

    getMapEnvelope: function() {
        var map = this.mapPanel.getMap();
        var viewRect = map.GetMapView();
        var envelope = [viewRect.TopLeftLatLong.Latitude, viewRect.TopLeftLatLong.Longitude, viewRect.BottomRightLatLong.Latitude, viewRect.BottomRightLatLong.Longitude];
        return envelope;
    },

    getFilterOptions: function() {
        if ((this.filterParameters.length == 0) || (null == this.filterStartDt) || (null == this.filterEndDt)) {
            return {
                parameters: null,
                startDt: null,
                endDt: null
            };
        } else {
            return {
                parameters: this.filterParameters,
                startDt: this.filterStartDt,
                endDt: this.filterEndDt
            };
        }
    }
});

if (typeof (Sys) !== "undefined") { Sys.Application.notifyScriptLoaded(); }

