/** api: constructor
 *  .. class:: ProfileGrid(config)
 *
 *    Plugin for removing a selected layer from the map.
 *    TODO Make this plural - selected layers
 */
gxp.plugins.ProfileGrid = Ext.extend(gxp.plugins.Tool, {
    
    /** api: ptype = gxp_profileGrid */
    ptype: "gxp_profileGrid",
    	
	/** api: config[saveText]
     *  ``String``
     *  Text for save message header
     */
	saveText: "Save",
	
	/** api: config[windowTitle]
     *  ``String``
     *  Text for windows header
     */
	windowTitle: "Profile Manager",
	
	/** api: config[addProfileText]
     *  ``String``
     *  Text for windows header
     */
	addProfileText: "Add",
	
	/** api: config[profileTitleText]
     *  ``String``
     *  Text for column header
     */
	profileTitle: "Title",
	
	/** api: config[profileIdText]
     *  ``String``
     *  Text for column header
     */
	profileId: "Profile ID",
	
	/** api: config[ownerTitleText]
     *  ``String``
     *  Text for column header
     */
	profileOwner: "Owner",
	
	/** api: config[loadProfileBtn]
     *  ``String``
     *  Text for column header
     */
	loadProfileBtn: "Load profile",
	
	/** api: config[deleteBtnText]
     *  ``String``
     *  Text for column header
     */
	deleteBtnText: "Delete",
	
	/** api: config[doneText]
     *  ``String``
     *  Text for column header
     */
	doneText: "Done",
	
	/** api: config[ascText]
     *  ``String``
     *  Text for asc header menu button (i18n).
     */
    ascText: "Sort ascenging",
	
	/** api: config[descText]
     *  ``String``
     *  Text for desc header menu button  (i18n).
     */
    descText: "Sort descending",
	
	/** api: config[colText]
     *  ``String``
     *  Text for column header menu button  (i18n).
     */
    colText: "Columns",
	
	dateCreate: "Created",
	
    /** api: config[nonUploadSources]
     *  ``Array``
     *  If ``upload`` is enabled, the upload button will not be displayed for 
     *  sources whose identifiers or URLs are in the provided array.  By 
     *  default, the upload button will make an effort to be shown for all 
     *  sources with a url property.
     */

    /** api: config[relativeUploadOnly]
     *  ``Boolean``
     *  If ``upload`` is enabled, only show the button for sources with relative
     *  URLs (e.g. "/geoserver").  Default is ``true``.
     */
    relativeUploadOnly: true,

    /** api: config[startSourceId]
     * ``Integer``
     * The identifier of the source that we should start with.
     */
    startSourceId: null,
    
    /** private: property[selectedSource]
     *  :class:`gxp.plugins.LayerSource`
     *  The currently selected layer source.
     */
    selectedSource: null,

	/** private: property[windowsWidth]  
	 * ``Integer``
     */
    windowsWidth: 1000,
	
	/** private: property[windowsHeight]  
	 * ``Integer``
     */
    windowsHeight: 500,	
	
    /** private: method[constructor]
     */
    constructor: function(config) {        
        gxp.plugins.ProfileGrid.superclass.constructor.apply(this, arguments);        
    },
    
    
    /** api: method[showProfileWindow]
     * Shows the window with a profile grid.
     */
    showProfileGrid: function() {
        if(!this.profileGrid) {
            this.initProfileGrid();
        }
        this.profileGrid.show();
    },

    /**
     * private: method[initProfileGrid]
     * Constructs a window with a profile grid.
     */
    initProfileGrid: function() {
       
	   
		var profileStore = new Ext.data.ArrayStore({
			fields: ['dateCreate', 'profileId', 'profileName', 'profileObject', 'profileOwner', 'status', 'is_default' ],
			data: [],
			autoLoad: false
		})
	   
		var privateProfilesStore = new Ext.data.JsonStore({
			autoDestroy: true,
			autoLoad: true,
			url: app.restUrl + '/list.json?obj=gis.map'+"&owner=" + app.currentUser,
			//url: app.restUrl + '/list.json?obj=gis.map'+"&owner=" + "admin",
			storeId: 'privateProfilesStore',
			root: 'description',
			id: 'privateProfilesStore',
			fields: ['dateCreate', 'profileId', 'profileName', 'profileObject', 'profileOwner', 'status' ],
			listeners: {
				load : function (store, records, status) {
					if (records)  for(var i=0;i < records.length;i++) {
						//records[i].set('dateCreate', new Date(records[i].get('dateCreate')).toLocaleString());
						var date = new Date(records[i].get('dateCreate'));
						var dateStr = date.getFullYear()+'-'+(date.getMonth()+1)+'-'+date.getDate()+' '+date.getHours()+':'+date.getMinutes()+':'+date.getSeconds();
						records[i].set('dateCreate',dateStr);					
					}
					profileStore.add(privateProfilesStore.getRange());
				}
			}
		});
		
		var commonProfilesStore = new Ext.data.JsonStore({
			autoDestroy: true,
			autoLoad: true,
			url: app.restUrl + '/list.json?obj=gis.map'+"&owner=commonprofile",
			storeId: 'commonProfilesStore',
			root: 'description',
			id: 'commonProfilesStore',
			fields: ['dateCreate', 'profileId', 'profileName', 'profileObject', 'profileOwner', 'status' ],
			listeners: {
				load : function (store, records, status) {
					if (records)  for(var i=0;i < records.length;i++) {
						//records[i].set('dateCreate', new Date(records[i].get('dateCreate')).toLocaleString());
						var date = new Date(records[i].get('dateCreate'));
						var dateStr = date.getFullYear()+'-'+(date.getMonth()+1)+'-'+date.getDate()+' '+date.getHours()+':'+date.getMinutes()+':'+date.getSeconds();
						records[i].set('dateCreate',dateStr);
						if (records[i].get('profileOwner')=="commonprofile") {
							records[i].set('profileOwner',"Профиль общего назначения");
						} 
					}
					profileStore.add(commonProfilesStore.getRange());
				}
			}
		});
		
		
		
		var selectedRecord = -1;
        
		var profileGridPanel = new Ext.grid.GridPanel({
            id: "profileGridPanel",
			autoScroll: true,
			store: profileStore,
            flex: 1,
			region: "west",
            autoExpandColumn: "title",
            colModel: new Ext.grid.ColumnModel([
                {id: "title", header: this.profileTitle, dataIndex: "profileName", sortable: true, flex:1},
				{id: "id", header: this.profileId, dataIndex: "profileId", sortable: true, flex:1}, 
				{id: "dateCreateText", header: this.dateCreate, dataIndex: "dateCreate", sortable: true, flex:1},
				{id: "owner", header: this.profileOwner, dataIndex: "profileOwner", sortable: true, flex:1},
				{id: "preview", header: 'Предпросмотр', dataIndex: "profileId", renderer: function(value, meta, rec) {return '<div class="portlet-form-button portlet-icon-notext icon-map clickable-profilepreview" title="Предпросмотр профиля" style="margin:0 auto;" type="button" esimo-mapprofile="'+value+'"></div>';},sortable: false, flex:1},
				{id: "url", header: 'Ссылка', dataIndex: "profileId", renderer: function(value, meta, rec) {return '<a target="_blank" href="http://'+window.location.hostname+window.location.pathname+'?profileId='+value+'" class="portlet-form-button portlet-icon-notext icon-url" style="display:block;" title="Ссылка на профиль отдельно"></a>';},sortable: false, flex:1}
            ]),					
            listeners: {
                scope: this,				
				afterrender: function() {
					var menu = profileGridPanel.getView().hmenu.items;				
 					for (var i in menu.items) {
						if (menu.items[i].itemId=="asc") menu.items[i].text = this.ascText;
						else if (menu.items[i].itemId=="desc") menu.items[i].text = this.descText;
						else if (menu.items[i].itemId=="columns") menu.items[i].text = this.colText;
					}
				},
				rowclick: function(grid,row) {
					selectedRecord = row;
				}
            }
        });

		var refreshGrid = function(removed) {
			Ext.getCmp("profileGridPanel").getStore().removeAt(removed);;
		}
		
		var isAlreadyInUse = function(t) {
			var k = false;
			app.mapPanel.layers.each(function(record, index) {
				if (record.get("title") == t) {																		
					k = true;					
				}
			});					
			return k;
		}
		
		
        var profileGridToolbar = [
			{
				text: this.loadProfileBtn,
				iconCls: 'icon-profile-load',
				handler: function() {
					//(selectedRecord + 1) && (window.location = PREFERENCES_URL + "&mode=view&profileId="+profileStore.getAt(selectedRecord).data.profileId);
					$.ajax({
					  type: 'GET',
					  url: '/restserver/services/requests/get/'+profileStore.getAt(selectedRecord).data.profileId+'.json',
					  data: {},
					  success: function(json){
							try{
								setMapView(json);
							}catch(e){console.log(e.message);}	
							try{
								loadLayers(json);
							}catch(e){console.log(e.message);}	
					  },
					  error: function(jqXHR, textStatus, errorThrown){
							console.log(textStatus);console.log(errorThrown);
					  },
					  dataType: 'json'
					});
				}
			},{
				text: this.deleteProfileBtn,
				iconCls: 'icon-profile-remove',
				handler: function() {
					if (selectedRecord != '-1')
						$.ajax({
						  type: 'POST',
						  url: '/restserver/services/requests/admin/delete/'+profileStore.getAt(selectedRecord).data.profileId+'.json',
						  data: {},
						  success: function(json){
								refreshGrid(selectedRecord);
						  },
						  error: function(jqXHR, textStatus, errorThrown){
								console.log(textStatus);console.log(errorThrown);
						  },
						  dataType: 'json'
						});
				}
			}
		];
       
	    var items = {
            xtype: "container",
            region: "center",
            layout: "vbox",
            layoutConfig: {
                align: 'stretch'
            },
            items: [profileGridPanel]
        };
		
		//TODO use addOutput here instead of just applying outputConfig
        this.profileGrid = new Ext.Window(Ext.apply({
            title: this.windowTitle,
            closeAction: "hide",
            layout: "border",
            width: this.windowsWidth,						
			height: this.windowsHeight,
            modal: true,
			maximizable  : true,
            items: items,
            tbar: profileGridToolbar,
            listeners: {
                hide: function(win) {
                    profileGridPanel.getSelectionModel().clearSelections();
                },                
                scope: this
            }
        }, this.initialConfig.outputConfig));

	},	
    //ADDED from 354723574e
    /** private: method[ProfileGrid]
     *  :arg records: ``Array`` the layer records to add
     *  :arg source: :class:`gxp.plugins.LayerSource` The source to add from
     *  :arg isUpload: ``Boolean`` Do the layers to add come from an upload?
     */   
   ProfileGrid: function(records, source, isUpload) {
        source = source || this.selectedSource;
        var layerStore = this.target.mapPanel.layers,
            extent, record, layer;
        for (var i=0, ii=records.length; i<ii; ++i) {
            record = source.createLayerRecord({
                name: records[i].get("name"),
                source: source.id
            });
            if (record) {
                layer = record.getLayer();
                if (layer.maxExtent) {
                    if (!extent) {
                        extent = record.getLayer().maxExtent.clone();
                    } else {
                        extent.extend(record.getLayer().maxExtent);
                    }
                }
                if (record.get("group") === "background") {
                    layerStore.insert(0, [record]);
                } else {
                    layerStore.add([record]);
                }
            }
        }
        if (extent) {
            this.target.mapPanel.map.zoomToExtent(extent);
        }
        if (isUpload && this.postUploadAction && records.length === 1 && record) {
            // show LayerProperties dialog if just one layer was added
            this.target.selectLayer(record);
            var outputConfig,
                actionPlugin = this.postUploadAction;
            if (!Ext.isString(actionPlugin)) {
                outputConfig = actionPlugin.outputConfig;
                actionPlugin = actionPlugin.plugin;
            }
            this.target.tools[actionPlugin].addOutput(outputConfig);
        }
    }
    
	});
Ext.preg(gxp.plugins.ProfileGrid.prototype.ptype, gxp.plugins.ProfileGrid);
