﻿TNRIS.ODMLayer = function(config) {
    Ext.applyIf(this, {
        shapeLineColor: new VEColor(0,150,150,0.6),
        shapeFillColor: new VEColor(0,150,150,0.6),
        shapeIcon: '<div class="hurrtraxPushpin"><img src="images/pushPins/star.png" /></div>'
    });
    
    TNRIS.ODMLayer.superclass.constructor.call(this, config );
};

Ext.extend(TNRIS.ODMLayer, TNRIS.ShapeLayer, {
    
    getUSPName: function(context) {
        return 'findODMSpatialRecords';
    },
    
    getBaseParams: function() {
        return {layerId: this.layerId(), network: this.getOdmNetworkName() };
    },
    
    smartable: function(value) {
        return false;
    },
    
    getLinkButtonDescription: function(record) {
        var cmpId = this.getId();
        var recordId = record.id;
        var link = String.format('<div class="linkButton"><a href="#" onclick="ShapeLayerFunctionProxy(\'viewSiteDetails\', \'{0}\', [\'{1}\'])">view details</a> >></div>', cmpId, recordId);
        return link;
    },
    
    getOdmNetworkName: function() {
        return this.config.odmNetworkName;
    },

    viewSiteDetails: function(args) {
        var recordId = args[0];
        var record = this.getShapeStore().getById(recordId);
        
        var url = this.getVirtualEarthUrl();
        var siteId = record.get('Site Code');
        var networkName = this.getOdmNetworkName();

        var win = this.getODMDataViewer();
        win.load({url:url, siteId: siteId,network: networkName});
        win.show();
    },
    
    getODMDataViewer: function() {
        var window = Ext.getCmp('ODMSiteDetailsWindow');
        if (null == window) {
            window = new TNRIS.ODMSiteDetailsWindow({id: 'ODMSiteDetailsWindow'});
        }
        else {
            window.resetWindow();
        }
        return window;
    }
});


TNRIS.ODMSiteDetailsWindow = function(config) {
    Ext.apply(this,config);
    this.datePicker = new Ext.DatePicker({ hidden: true, cancelText: 'Cancel', id: 'odmDatePicker', cls: 'odmDatePicker' });
    this.sm = new Ext.grid.CheckboxSelectionModel({singleSelect:false});
    this.selectionGrid = new Ext.grid.GridPanel({
        id:'selectionGrid',
        cls: 'selectionGrid',
        title: 'Variables Measured:',
        height: 150,
        width:496,
        scope: this,
        maskDisabled: false,
        tools: [{
            id: 'refresh',
            handler: function(e, toolEl, panel) {
                this.refreshSelectionGrid();
            },
            scope: this
        }],
        columns: [this.sm],
        sm: this.sm,
        store: new Ext.data.Store({
            id: 'selectionGridStore',
            autoLoad: false })
    });
    
    this.tabs = new Ext.TabPanel({
        layoutOnTabChange: true,
        id: 'detailsTab',
        cls: 'detailsTab',
        height:250,
        width: 498,
        enableTabScroll: true,
        autoDestroy: true
    });
    
    TNRIS.ODMSiteDetailsWindow.superclass.constructor.call(this, {
        title: 'Site Details',
        closable: true,
        closeAction: 'close',
        cls:'clsSiteDetails',
        //layout: 'fit',
        resizable: false,
        height:400,
        width: 500,
        modal: true,
        items: 
        {
            xtype: 'form',
            id:'siteDetailsForm',
            defaultType: 'textfield',
            border: false,
            items: [
                {
                    xtype:'fieldset',
                    cls:'beginDateFieldset',
                    id: 'beginDateFieldset',
                    width: 300,
                    height: 50,
                    items: [
                        {
                            xtype: 'textfield',
                            id: 'beginDate',
                            cls: 'beginDate',
                            fieldLabel: "Begin Date",
                            emptyText: 'yyyy-mm-dd',
                            width: 80
                        },
                        {
                            xtype: 'button',
                            id: 'beginDatePicker',
                            cls: 'datepickerButton',
                            handler: function() {
                                this.datePicker.on('select',function(datepicker,date){
                                    Ext.getCmp('beginDate').setValue(date.format('yyyy-MM-dd'));
                                    datepicker.purgeListeners();
                                    datepicker.hide();
                                },this);
                                this.datePicker.show();
                            },
                            scope: this
                        }
                    ]
                },

                
                {
                    xtype:'fieldset',
                    cls: 'endDateFieldset',
                    id: 'endDateFieldset',
                    width: 300,
                    height: 50,
                    items: [
                        {
                            xtype: 'textfield',
                            id: 'endDate',
                            cls: 'endDate',
                            fieldLabel: "End Date",
                            emptyText: 'yyyy-mm-dd',
                            width:80
                        },
                        {
                            xtype: 'button',
                            id: 'endDatePicker',
                            cls: 'datepickerButton',
                            handler: function() {
                                this.datePicker.on('select',function(datepicker,date){
                                    Ext.getCmp('endDate').setValue(date.format('yyyy-MM-dd'));
                                    datepicker.hide();
                                },this);
                                this.datePicker.show();
                            },
                            scope: this
                        }
                    ]
                },
                this.datePicker,
                this.selectionGrid,
                {
                    xtype: 'button',
                    id: 'get-details',
                    text: 'Fetch Details',
                    handler: this.onGetDetailsBtnClick,
                    scope: this
                },
                this.tabs
            ]
        }
    });
    this.on('show',this.onRenderComplete,this);
};

Ext.extend(TNRIS.ODMSiteDetailsWindow, Ext.Window, {
    
    onRenderComplete: function() {
        this.refreshSelectionGrid();
    },
    
    load: function(siteInfo) {
        this.siteId = siteInfo.siteId;
        this.siteUrl = siteInfo.url;
        this.network = siteInfo.network;
        this.setWindowTitle(this.siteId);
    },
    
    resetWindow: function() {
         this.refreshSelectionGrid();
    },
    
    onGetDetailsBtnClick: function() {
        this.refreshDetailsGrid();
    
    },
    setWindowTitle: function(value){
        value && this.setTitle('Site Code:' + value);
    },
    
    refreshSelectionGrid: function() {
        Ext.get('selectionGrid').mask('Loading variables measured at this site...');
        PageMethods.findOdmVariablesForSite(this.siteUrl, this.network, this.siteId, function(result) {
            if (null != result.error) {
                Ext.get('selectionGrid').mask(result.error);
                return;
            }
            
            var store = new Ext.data.Store({
                id: 'selectionGridStore',
                autoLoad: false,
                reader: new Ext.data.ArrayReader({}, this.getRecordForGridData(result))
            });
            store.loadData(result.data);
            
            var columns = [];
            columns.push(this.sm);
            Ext.each(this.getColumnSpecForGridData(result), function(value){columns.push(value);} , this );
            
            var grid = Ext.getCmp('selectionGrid');
            if (grid !=null) { 
                grid.reconfigure(store,new Ext.grid.ColumnModel(columns)); 
                Ext.get('selectionGrid').unmask();
            }
        }.bind(this));
    },
    
    refreshDetailsGrid: function() {
        if (! this.validateInput()){
            return;
        }
        
        var beginDate = Ext.getCmp('beginDate').getValue();
        var endDate = Ext.getCmp('endDate').getValue();
        var siteSelections = this.sm.getSelections();
        
        this.tabs.getEl().mask('Loading time series information from remote service...');

        Ext.each(siteSelections,function(site){
            var variableCode = site.get('variableCode');
            var variableName =site.get('variableName');
            
            PageMethods.findOdmSiteVariableTimeSeries(this.siteUrl, this.network, this.siteId, variableCode,beginDate,endDate,function(result) {
                if (null != result.error) {
                    return;
                }

                var dataStore = new Ext.data.Store({
                    id: variableCode+'Store',
                    autoLoad: false,
                    reader: new Ext.data.ArrayReader({}, this.getRecordForGridData(result))
                });
                
                dataStore.loadData(result.data);

                var columns = [];
                Ext.each(this.getColumnSpecForGridData(result),function(value){
                    columns.push(value);
                },this);
                
                var grid = new Ext.grid.GridPanel({
                    cls: 'detailsGrid',
                    id: variableCode+'Grid',
                    title: variableName,
                    height:200,
                    width: 496,
                    scope: this,
                    store: dataStore,
                    cm: new Ext.grid.ColumnModel(columns)
                });
                
                this.tabs.add(grid);
                this.tabs.activate(variableCode+'Grid');
            }.bind(this));
        },this);
        this.tabs.getEl().unmask();
          
        this.tabs.doLayout();
    },
    
    getRecordForGridData: function(gridData) {
        var result = [];
        Ext.each(gridData.fields[0],function(value) {
            result.push({'name': value});
        },this);
        return Ext.data.Record.create(result) ;
    },    
    
    getColumnSpecForGridData: function(gridData) {
        var result = [];
        for (var i =0; i< gridData.fields[0].length; i++) {
            result.push({'dataIndex': gridData.fields[0][i] , 'header' : gridData.columnSpecs[0][i],'sortable':false});
        }
        return result;
    },
    
    validateInput: function() {
        //Date validation
        var dateValidation = false;
        var beginDate = Ext.getCmp('beginDate').getValue();
        var endDate = Ext.getCmp('endDate').getValue();

        var bt = Date.parseDate(beginDate,'Y-m-d');
        if (bt) {
            var et = Date.parseDate(endDate,'Y-m-d');
            if (et) {
                dateValidation = true;
            }
        }

        if (! dateValidation) {
            Ext.Msg.alert("Date Format Invalid", "Please specify Begin Date and End Date in YYYY-MM-DD format (Like 1999-01-21)");
            return false;
        }

        // Variable Select Validation
        var variableCode = Ext.getCmp('selectionGrid').getSelectionModel().getCount();
        if (variableCode == 0) {
            Ext.Msg.alert("Variable Not Selected", "Please select variable from the list of variables measured");
            return false;
        }
        return true;
    }
});

if (typeof(Sys) !== "undefined") { Sys.Application.notifyScriptLoaded(); }
