﻿/***************************************************************************************************************************
* LayerPalette: manages Available Layers list
* @constructor
* @extends Ext.Panel
****************************************************************************************************************************/
TNRIS.LayerPalette = function (config) {
    Ext.apply(this, config);

    // LayerRecord is built from server callback (GridData.getClientFields())
    this.LayerRecord = Ext.data.Record.create([
        {name: 'id'}
    ]);

    var layerReader = new Ext.data.ArrayReader({
        id: 0                     // The subscript within row Array that provides an ID for the Record (optional)
    }, this.LayerRecord);

    this.layerStore = Ext.StoreMgr.lookup('layerStore');
    this.layerStore.on('load', this.filterStores, this);
    
    this.tpl = new Ext.XTemplate(
        '<tpl for=".">',
        '    <div class="layerModule" name="{name}">',
        '        <div class="draggableLayer" id="{[Ext.id()]}">',
        '        <img src="{micronail_url}" class="microNail" alt="Drag to add layer to Map" />',
        '        <h1 class="layerNameIdentifier">{name}</h1>',
        '        <p class="layerTeaser">{teaser}',
        '       <tpl if="description.length &gt; 0">',
        '       <span class="showDescriptionText">Full Info</span>',
        '       </tpl>',
        '       </p>',
        '       <tpl if="queryable == 1">',
        '           <span class="gridButton">Grid</span>',
        '           <tpl if="source_type != \'xml\'">',
        '            <span class="smartLayerButton">Smart</span>',
        '           </tpl>',
        '       </tpl>',
        '    </div>',
        '    </div>',
        '</tpl>');
    this.tpl = this.tpl.compile();
    
    this.dataView = new TNRIS.LayerDataView({
        store: this.layerStore,
        title: 'Source Details',
        tpl: this.tpl,
        cls: 'layerList',
        autoScroll: true,
        multiSelect: true,
        overClass: 'x-view-over',
        itemSelector: 'div.layerModule',
        loadMask: {msg: 'Loading Layers...'},
        layout: 'fit',
        emptyText: '<p class="NAlayers">No available layers.</p>',
        mapPanel: this.mapPanel,
        listeners: {
            'dblclick': {scope: this, fn: this.onDoubleClick},
            'click':    {scope: this,fn: this.onClick}
        }
    });
    
    var tagTpl = new Ext.XTemplate(
        '<tpl for=".">',
        '   <div class="tagNode unselectable"><div class="tagNodeLeft"></div><div class="tagNodeCenter" ext:qtitle="Description" ext:qtip="{description}">{name}</div><div class="tagNodeRight"></div></div>',
        '</tpl>').compile();
    
    var TagRecord = Ext.data.Record.create([
        {name: 'id'}
    ]);

    var tagReader = new Ext.data.ArrayReader({
        id: 0                     // The subscript within row Array that provides an ID for the Record (optional)
    }, TagRecord);

    var tagProxy = new TNRIS.FunctionProxy({findAll: 'findAllTags'});
    this.tagStore = new Ext.data.Store({
        id: 'tagStore',
        proxy: tagProxy,
        sortInfo: {field: "name", direction: "ASC"},
        reader: tagReader,
        autoLoad: true,
        /*There was a bug in the panel as it does not render correctly. https://extjs.com/forum/showthread.php?t=30026 */
        listeners: {'load': {scope: this, fn: function() {this.setSize(); this.ownerCt.doLayout(); this.doLayout();}}}
    });
    
    tagProxy.store = this.tagStore;

    var tagDataView = new Ext.DataView({
        id: 'tagCloud',
        tpl: tagTpl,
        layout: 'fit',
        singleSelect: true,
        store: this.tagStore,
        overClass: 'tag-over',
        itemSelector: 'div.tagNode',
        listeners: {
            'selectionchange': {
                scope: this,
                fn: this.onTagChange
            }
        }
    });

    TNRIS.LayerPalette.superclass.constructor.call(this, 
        Ext.apply({
            items: new Ext.TabPanel({
                id:'layersTabPanel',
                activeTab: 0,
                items: [
                    this.dataView//,
                    //this.userDataView
                    ]
            }),
            tools: [
                {
                    id: 'refresh',
					cls: 'x-btn-text',
					text: 'Refresh Layers',
                    handler: function(e, toolEl, panel) {
                        this.layerStore.reload();
                        this.tagStore.reload();
                    },
                    scope: this
                }
            ],
            layout: 'fit',
            tbar: [ tagDataView ]
        }, config));

    this.mapPanel.on({
        'map-change': {
            scope: this,
            fn: this.onMapChange
        }
    });
    
};

Ext.extend(TNRIS.LayerPalette, Ext.Panel, 
    /** @scope TNRIS.LayerPalette */
    {
    onMapChange: function(args) {
        // TODO : check if the layer removed is a USER layer
        if (args.remove != null && args.remove.length > 0) {

        } else {
            this.filterStores();
        }
    },
    
    filterStores: function() {
        // remove all layers from the palette that are found in the map's list of layers
        var layerIds = this.mapPanel.getLayers().collect(function(layer) {
            return layer.layerId();
        });

        this.layerStore.filterBy(function(r, id) {
            return (layerIds.indexOf(id) == -1);
        });
        
    },
    
    onDoubleClick: function(panel, index, node, e) {
        var r = panel.getRecord(node);
        var layer = TNRIS.LayerFactory.createLayerFromRecord(r);
        this.mapPanel.addLayer(layer);
    }, 
    
    onClick: function(panel, index, node, e) {
        var elementClicked= e.getTarget();
        var record = panel.getRecord(node);
        
        if (elementClicked.href) {
                   window.open(elementClicked.href);            
        }
        
        // "Full Info" links open a window
        if (Ext.fly(elementClicked).hasClass('showDescriptionText')) {
           
            if (Ext.WindowMgr.get('descriptionDialog')) {
                Ext.WindowMgr.get('descriptionDialog').close();
            }
            
            var descriptionDialog = new Ext.Window({
                    id: 'descriptionDialog',
                    width: 400,
                    //autoHeight: true,
                    autoScroll: true,
                    resizable: true,
                    stateful: false,
					cls: 'fullDescription',
                    modal: false,
                    title: record.get('name'),
                    html: record.get('description'),
                    buttonAlign: 'center',
                    buttons: [{
                        text: 'Ok',
                        handler: function() {
                            descriptionDialog.close();
                        }
                    }],
                    defaultButton: 0,
                    bodyStyle: {padding: "10px" },
                    plain: true
                });
            descriptionDialog.show(elementClicked);
        }
        
        var layer;
                // setup view_data button if it exists
        if (Ext.fly(elementClicked).hasClass('gridButton')) {
            // TODO: don't create a new layer if one already exists for this record
            layer = TNRIS.LayerFactory.createLayerFromRecord(record);
            Ext.getCmp('infoPanel').addLayerToGrid(layer);
        }

        // setup smartlayer button if it exists
        var mapPanel = this.mapPanel;
        if (Ext.fly(elementClicked).hasClass('smartLayerButton')) {
            // TODO: don't create a new layer if one already exists for this record
            layer = TNRIS.LayerFactory.createLayerFromRecord(record);
            var win = new TNRIS.SmartLayerWindow({layer: layer, onSuccess: function(smartLayer) {
                mapPanel.addLayer(smartLayer);
            }.bind(this)});
            win.show();
        }
    }, 

    onTagChange: function(dv, selections) {
        Ext.getCmp('layersTabPanel').activate(this.dataView);
        
        if (selections.length == 0) {
            return;
        }
        
        var selected = selections.first();
        if (this.lastSelected == selected) {
            this.lastSelected = null;
            this.layerStore.reload({params: null});
            dv.clearSelections();
        } else {
            var tagId = dv.getSelectedRecords().first().id;
            this.lastSelected = selected;
            this.layerStore.reload({params: tagId});
        }
    },
    
    onContextMenu: function (dataview, index, node, e) {
        var record = dataview.getRecord(node);
        this.ctxLayer = TNRIS.LayerFactory.createLayerFromRecord(record);

        //context menu for nhd user layer
        if (this.ctxLayer.xmlLayerType && ((this.ctxLayer.xmlLayerType()=='NHDUserLayer')||(this.ctxLayer.xmlLayerType()=='NFIPUserLayer'))){
            if (!this.nhdMenu) {
                this.nhdMenu = new Ext.menu.Menu({
                    id:"layer-palette-nhd-menu", 
                    cls: 'layerPaletteMenu',
                    items:[{
                            id:"exportNndLayer", 
                            icon: '../images/buttons/edit.png',
                            cls: 'exportNhdLayerCtxMenuItem',
                            text:"Export Layer", 
                            scope: this, 
                            handler:function (btn, e) {
                                btn.parentMenu.hide();
                                this.ctxLayer.getLayerExportWindow().show();
                            }
                        }]
                });
                this.nhdMenu.on('hide', this.onContextHide, this);
            }
            e.stopEvent();
            this.nhdMenu.showAt(e.getXY());
            return;
        }

        //context menu for all user layers
        if (!this.menu) {
            this.menu = new Ext.menu.Menu({
                id:"layer-palette-menu", 
                cls: 'layerPaletteMenu',
                items:[{
                        id:"editLayer", 
                        icon: '../images/buttons/edit.png',
                        cls: 'editLayerCtxMenuItem',
                        text:"Edit Layer", 
                        scope: this, 
                        handler:function (btn, e) {
                            var win = new TNRIS.UserLayerWindow({
                                layer: this.ctxLayer,
                                mapPanel: this.mapPanel
                            });
                            btn.parentMenu.hide();
                            win.show();
                        }
                    },{
                        id:"removeLayer", 
                        icon: '../images/buttons/delete.png',
                        cls: 'removeLayerCtxMenuItem',
                        text:"Remove Layer", 
                        scope: this, 
                        handler:function (btn, e) {
                            btn.parentMenu.hide();
                            Ext.Msg.confirm('Are you Sure?', 'Do you wish to permanently remove the "' + this.ctxLayer.name() + '" layer?', function(btn) { 
                                if (btn == 'yes') {
                                    PageMethods.removeUserLayer(this.ctxLayer.layerId(), function(result) {
                                        if (result != null && result.length > 0) {
                                            Ext.Msg.alert("Failed", "This layer was unable to be removed.  " + result);
                                        } else {
                                            gemss.app.msg('Layer Removed', "The '{0}' layer has been removed", this.ctxLayer.name());
                                            Ext.StoreMgr.lookup('userLayerStore').reload();
                                        }
                                    }.bind(this));
                                }
                            }, this);
                        }
                    },{
                        id:"exportLayer", 
                        icon: '../images/buttons/import_export.png',
                        cls: 'exportLayerCtxMenuItem',
                        text:"Export Layer", 
                        scope: this, 
                        handler:function (btn, e) {
                            btn.parentMenu.hide();
                            if (this.exportLayerWindow == null) {
                                this.exportLayerWindow = new Ext.Window({
                                    id: 'exportLayerWindow',
                                    width: 400,
                                    height: 200,
                                    modal: true,
                                    closeAction: 'hide',
                                    items: 
                                        new Ext.form.FormPanel({
                                            items: {
                                                xtype: 'combo',
                                                id: 'exportFormatType',
                                                fieldLabel: "Select a Format",
                                                mode: 'local',
                                                hiddenName: 'formatType',
                                                editable: false,
                                                forceSelection: true,
                                                width: 250,
                                                triggerAction: 'all',  // don't filter the list by the current selection - always display all available choices
                                                store: [['csv', 'Comma Seperated Values'], ['kml', 'KML'], ['georss', 'GeoRSS']],
                                                value: 'csv'
                                            }
                                        }),
                                    buttonAlign: 'center',
                                    buttons: [
                                        {
                                            text: 'Export',
                                            scope: this,
                                            handler: function() { 
                                                var format = this.exportLayerWindow.findById('exportFormatType').getValue();
                                                // './download redirects to a downloader httphandler
                                                window.open('./download/' + this.ctxLayer.name() + '.' + format + "?l=" + this.ctxLayer.layerId() + "&f=" + format);
                                                this.exportLayerWindow.hide();
                                            }
                                        },{ 
                                            text: 'Cancel',
                                            scope: this,
                                            handler: function() { this.exportLayerWindow.hide(); }
                                        }
                                    ]
                                });
                            }
                            this.exportLayerWindow.setTitle('Export the "' + this.ctxLayer.name() + '" Layer...');
                            this.exportLayerWindow.show();
                        }
                    }]
                });
            this.menu.on('hide', this.onContextHide, this);
        }
        e.stopEvent();
        this.menu.showAt(e.getXY());
    },
    
    onContextHide: function() {
        
    }
});


TNRIS.LayerDataView = function(config) {
    Ext.apply(this, config);
    TNRIS.LayerDataView.superclass.constructor.call(this);

    this.draggableLayers = [];
};

Ext.extend(TNRIS.LayerDataView, Ext.DataView, {
    refresh: function() {
        this.draggableLayers.each(function(el, index) {
            el.unreg();
        });
        this.draggableLayers.clear();

        var result = TNRIS.LayerDataView.superclass.refresh.call(this);
    
        var drags = this.getEl().select('.draggableLayer');
        var dragFn = function(e, id) {
            var target = Ext.dd.DragDropMgr.getDDById(id);
            target.mapPanel.addLayer(this.config.layer);
        };
        
        drags.each(function(el, dv, index) {
            // setup drag and drop
            var node = this.findItemFromChild(el);
            var record = this.getRecord(node);
            var layer = TNRIS.LayerFactory.createLayerFromRecord(record);
            var dd = new Ext.dd.DDProxy(el.dom.id, 'mapLayer', {
                layer: layer
            });
            dd.onDragDrop = dragFn.bind(dd);
            
        }.bind(this));
        return result;
    }
    
});

if (typeof(Sys) !== "undefined") { Sys.Application.notifyScriptLoaded(); }
