package org.gcube.portlets.user.workspace.client;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.gcube.portlets.user.workspace.client.ConstantsExplorer.ViewSwitchType;
import org.gcube.portlets.user.workspace.client.ConstantsPortlet.ViewSwitchTypeInResult;
import org.gcube.portlets.user.workspace.client.event.ActiveGroupingView;
import org.gcube.portlets.user.workspace.client.event.ActiveGroupingViewHandler;
import org.gcube.portlets.user.workspace.client.event.AddFolderEvent;
import org.gcube.portlets.user.workspace.client.event.AddFolderEventHandler;
import org.gcube.portlets.user.workspace.client.event.AddSmartFolderEvent;
import org.gcube.portlets.user.workspace.client.event.DeleteItemEvent;
import org.gcube.portlets.user.workspace.client.event.DeleteItemEventHandler;
import org.gcube.portlets.user.workspace.client.event.DeleteMessageEvent;
import org.gcube.portlets.user.workspace.client.event.DeleteMessageEventHandler;
import org.gcube.portlets.user.workspace.client.event.DoubleClickElementSelectedEvent;
import org.gcube.portlets.user.workspace.client.event.DoubleClickElementSelectedEventHandler;
import org.gcube.portlets.user.workspace.client.event.FileDownloadEvent;
import org.gcube.portlets.user.workspace.client.event.FileDownloadEventHandler;
import org.gcube.portlets.user.workspace.client.event.FileUploadEvent;
import org.gcube.portlets.user.workspace.client.event.FileUploadEventHandler;
import org.gcube.portlets.user.workspace.client.event.FilterScopeEvent;
import org.gcube.portlets.user.workspace.client.event.GridElementSelectedEvent;
import org.gcube.portlets.user.workspace.client.event.GridElementSelectedEventHandler;
import org.gcube.portlets.user.workspace.client.event.GridElementUnSelectedEvent;
import org.gcube.portlets.user.workspace.client.event.GridElementUnSelectedEventHandler;
import org.gcube.portlets.user.workspace.client.event.ImagePreviewEvent;
import org.gcube.portlets.user.workspace.client.event.ImagePreviewEventHandler;
import org.gcube.portlets.user.workspace.client.event.LoadAllScopeEvent;
import org.gcube.portlets.user.workspace.client.event.LoadAllScopeEventHandler;
import org.gcube.portlets.user.workspace.client.event.OpenContextMenuTreeEvent;
import org.gcube.portlets.user.workspace.client.event.OpenContextMenuTreeEventHandler;
import org.gcube.portlets.user.workspace.client.event.OpenReportsEvent;
import org.gcube.portlets.user.workspace.client.event.OpenReportsEventHandler;
import org.gcube.portlets.user.workspace.client.event.PathElementSelectedEvent;
import org.gcube.portlets.user.workspace.client.event.PathElementSelectedEventHandler;
import org.gcube.portlets.user.workspace.client.event.PreviewMessageEvent;
import org.gcube.portlets.user.workspace.client.event.PreviewMessageEventHandler;
import org.gcube.portlets.user.workspace.client.event.RenameItemEvent;
import org.gcube.portlets.user.workspace.client.event.RenameItemEventHandler;
import org.gcube.portlets.user.workspace.client.event.SaveAttachmentsEvent;
import org.gcube.portlets.user.workspace.client.event.SaveAttachmentsEventHandler;
import org.gcube.portlets.user.workspace.client.event.SaveSmartFolderEvent;
import org.gcube.portlets.user.workspace.client.event.SaveSmartFolderEventHandler;
import org.gcube.portlets.user.workspace.client.event.ScopeChangeEvent;
import org.gcube.portlets.user.workspace.client.event.ScopeChangeEventHandler;
import org.gcube.portlets.user.workspace.client.event.SearchTextEvent;
import org.gcube.portlets.user.workspace.client.event.SearchTextEventHandler;
import org.gcube.portlets.user.workspace.client.event.SendMessageEvent;
import org.gcube.portlets.user.workspace.client.event.SendMessageEventHandler;
import org.gcube.portlets.user.workspace.client.event.WebDavUrlEvent;
import org.gcube.portlets.user.workspace.client.event.WebDavUrlEventHandler;
import org.gcube.portlets.user.workspace.client.interfaces.EventsTypeEnum;
import org.gcube.portlets.user.workspace.client.interfaces.SubscriberInterface;
import org.gcube.portlets.user.workspace.client.model.FileGridModel;
import org.gcube.portlets.user.workspace.client.model.FileModel;
import org.gcube.portlets.user.workspace.client.model.FolderModel;
import org.gcube.portlets.user.workspace.client.model.ScopeModel;
import org.gcube.portlets.user.workspace.client.view.WorskpacePortlet;
import org.gcube.portlets.user.workspace.client.view.panels.GxtBorderLayoutPanel;
import org.gcube.portlets.user.workspace.client.view.panels.GxtItemsPanel;
import org.gcube.portlets.user.workspace.client.view.windows.MessageBoxAlert;
import org.gcube.portlets.user.wsmail.client.forms.MailForm;

import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.RunAsyncCallback;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.HasWidgets;

/**
 * 
 * @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
 *
 */
public class AppController implements SubscriberInterface {
	private final static HandlerManager eventBus = new HandlerManager(null);
	private WorskpacePortlet wsPortlet = null;
	private AppControllerExplorer appContrExplorer = null;
	private String rootIdentifier = null;
	public static boolean isSearchActive = false;

	public AppController(AppControllerExplorer appControllerExplorer) {
		this.appContrExplorer = appControllerExplorer;
		this.appContrExplorer.subscribe(this, new EventsTypeEnum[] {
				EventsTypeEnum.RENAME_ITEM_EVENT, 
				EventsTypeEnum.SELECTED_ITEM_EVENT,
				//				EventsTypeEnum.EXPAND_FOLDER_EVENT,
				EventsTypeEnum.ADDED_FOLDER_EVENT,
				EventsTypeEnum.DELETE_ITEM_EVENT,
				EventsTypeEnum.SUBTREE_LOAD_EVENT,
				EventsTypeEnum.SMART_FOLDER_EVENT,
				EventsTypeEnum.COMPLETED_FILE_UPLOAD_EVENT,
				EventsTypeEnum.ADDED_FILE_EVENT,
				EventsTypeEnum.MOVED_ITEM_EVENT,
				EventsTypeEnum.LOAD_MESSAGES_EVENT,
				EventsTypeEnum.SWITCH_VIEW_EVENT,
				EventsTypeEnum.DELETED_MESSAGE,
				EventsTypeEnum.MARK_MESSAGE_AS_READ,
				EventsTypeEnum.REFRESH_FOLDER,
				EventsTypeEnum.SELECTED_MESSAGE,
				EventsTypeEnum.CREATE_NEW_MESSAGE,
				EventsTypeEnum.REPLY_FORWARD_MESSAGE
		});
		bind();
	}

	public static HandlerManager getEventBus() {
		return eventBus;
	}

	private void bind() {
		// History.addValueChangeHandler(this);

		//********EVENTS TO NOTIFY SUBSCRIBERS
		eventBus.addHandler(ActiveGroupingView.TYPE, new ActiveGroupingViewHandler() {
			
			@Override
			public void onActiveGroupingView(ActiveGroupingView activeGroupingView) {
				
				if(activeGroupingView.isActiveGrouping()){
					setCookieGridViewSetting("true");
					wsPortlet.getGridGroupContainer().enableGrouping();
				}
				else{
					setCookieGridViewSetting("false");
					wsPortlet.getGridGroupContainer().disableGrouping();
				}
				
			}
		});

		eventBus.addHandler(OpenReportsEvent.TYPE, new OpenReportsEventHandler() {

			@Override
			public void onClickOpenReports(OpenReportsEvent openReportsEvent) {

				AppControllerExplorer.getEventBus().fireEvent(new OpenReportsEvent(openReportsEvent.getSourceFileModel()));

			}
		});

		eventBus.addHandler(PreviewMessageEvent.TYPE, new PreviewMessageEventHandler() {

			@Override
			public void onPreviewMessage(PreviewMessageEvent previewMessageEvent) {
				AppControllerExplorer.getEventBus().fireEvent(new PreviewMessageEvent(previewMessageEvent.getMessageIdentifier(), previewMessageEvent.getMessageType()));

			}
		});

		eventBus.addHandler(WebDavUrlEvent.TYPE, new WebDavUrlEventHandler() {

			@Override
			public void onClickWebDavUrl(WebDavUrlEvent webDavUrlEvent) {
				AppControllerExplorer.getEventBus().fireEvent(new WebDavUrlEvent(webDavUrlEvent.getItemIdentifier()));

			}

		});


		eventBus.addHandler(OpenContextMenuTreeEvent.TYPE, new OpenContextMenuTreeEventHandler() {

			@Override
			public void onOpenContextMenuTree(OpenContextMenuTreeEvent openContextMenuTreeEvent) {
				AppControllerExplorer.getEventBus().fireEvent(openContextMenuTreeEvent);


			}
		});

		eventBus.addHandler(ImagePreviewEvent.TYPE, new ImagePreviewEventHandler() {

			@Override
			public void onClickPreview(ImagePreviewEvent imgPrevEvnt) {
				AppControllerExplorer.getEventBus().fireEvent(new ImagePreviewEvent(imgPrevEvnt.getSourceFileModel(), imgPrevEvnt.getClientX(), imgPrevEvnt.getClientY()));

			}

		});

		eventBus.addHandler(FileDownloadEvent.TYPE, new FileDownloadEventHandler() {

			@Override
			public void onFileDownloadEvent(FileDownloadEvent fileDownloadEvent) {
				AppControllerExplorer.getEventBus().fireEvent(new FileDownloadEvent(fileDownloadEvent.getItemIdentifier(), fileDownloadEvent.getItemName(), fileDownloadEvent.getDownloadType()));
			}
		});

		eventBus.addHandler(DeleteMessageEvent.TYPE, new DeleteMessageEventHandler() {

			@Override
			public void onDeleteMessage(DeleteMessageEvent deleteMessageEvent) {
				AppControllerExplorer.getEventBus().fireEvent(new DeleteMessageEvent(deleteMessageEvent.getMessageTarget()));
			}

		});

		eventBus.addHandler(SaveAttachmentsEvent.TYPE, new SaveAttachmentsEventHandler() {

			@Override
			public void onSaveAttachments(SaveAttachmentsEvent saveAttachmentsEvent) {
				AppControllerExplorer.getEventBus().fireEvent(new SaveAttachmentsEvent(saveAttachmentsEvent.getMessageIdentifier(), saveAttachmentsEvent.getMessageType()));

			}
		});

		eventBus.addHandler(GridElementSelectedEvent.TYPE, new GridElementSelectedEventHandler() {

			@Override
			public void onGridElementSelected(GridElementSelectedEvent event) {

				doElementGridSelected(true, event.getSourceFile());

				//					setFileDetailsInView(event.getSourceFile().getIdentifier());

			}
		});

		eventBus.addHandler(LoadAllScopeEvent.TYPE, new LoadAllScopeEventHandler() {

			@Override
			public void onLoadScopes(LoadAllScopeEvent loadAllScopeEvent) {
				doLoadAllScope();

			}

			private void doLoadAllScope() {

				appContrExplorer.getRpcWorkspaceService().getAllScope(new AsyncCallback<List<ScopeModel>>() {

					@Override
					public void onFailure(Throwable caught) {
						new MessageBoxAlert("Error", ConstantsExplorer.SERVER_ERROR + " getting all scope." +ConstantsExplorer.TRY_AGAIN, null);
					}

					@Override
					public void onSuccess(List<ScopeModel> result) {

						//						for(ScopeModel scope: result)
						//							System.out.println("#############Scopde id " + scope.getId() + " name " + scope.getName());

						if(result!=null && result.size()>0){
							wsPortlet.getSearchAndFilterContainer().setListScope(result);
							wsPortlet.getSearchAndFilterContainer().selectScopeByIndex(0); //select first scope
						}
						else
							new MessageBoxAlert("Error", ConstantsExplorer.SERVER_ERROR + " getting all scope. No scope available. " +ConstantsExplorer.TRY_AGAIN, null);
							
					}
				});
			}
		});

		eventBus.addHandler(ScopeChangeEvent.TYPE, new ScopeChangeEventHandler() {

			@Override
			public void onLoadScope(ScopeChangeEvent scopeChangeEvent) {
				doLoadScope(scopeChangeEvent.getScopeId());

			}

			private void doLoadScope(String scopeId) {
				AppControllerExplorer.getEventBus().fireEvent(new FilterScopeEvent(scopeId));

			}
		});

		eventBus.addHandler(SaveSmartFolderEvent.TYPE, new SaveSmartFolderEventHandler() {

			@Override
			public void onSaveSmartFolder(SaveSmartFolderEvent saveSmartFolderEvent) {
				doSaveSmartFolder(saveSmartFolderEvent);

			}

			private void doSaveSmartFolder(SaveSmartFolderEvent event) {

				AppControllerExplorer.getEventBus().fireEvent(new AddSmartFolderEvent(event.getSearchText()));

			}
		});

		eventBus.addHandler(DoubleClickElementSelectedEvent.TYPE, new DoubleClickElementSelectedEventHandler() {

			@Override
			public void onDoubleClickElementGrid(DoubleClickElementSelectedEvent doubleClickElementSelectedEvent) {
				
				doElementDoubleClick(doubleClickElementSelectedEvent.getSourceFile());

			}

			private void doElementDoubleClick(final FileGridModel fileModel) {
//				appContrExplorer.expandFolder(event.getIdentifier());
				
				//COMMENTED 01-02-2013
//				appContrExplorer.expandFolder(event.getIdentifier());
				
				FolderModel folder = new FolderModel(fileModel.getIdentifier(), fileModel.getName(), fileModel.getParentFileModel(), true, fileModel.isShared());
				updateStoreByRpc(folder);

			}
		});

		eventBus.addHandler(SearchTextEvent.TYPE, new SearchTextEventHandler() {

			@Override
			public void onSearchText(SearchTextEvent searchTextEvent) {

				if(searchTextEvent.getTextSearch()==null){
					appContrExplorer.searching(false);
					wsPortlet.getGridGroupContainer().setBorderAsOnSearch(false);
				}
				else{
					wsPortlet.getSearchAndFilterContainer().setSearchActive(true); //ADDED 06-04-12
					isSearchActive = true;
					appContrExplorer.searching(true);
					doSearchText(searchTextEvent.getTextSearch());
				}
			}

			private void doSearchText(String textSearch) {

				if(wsPortlet.getGxtCardLayoutResultPanel().getActivePanel() instanceof GxtItemsPanel){ //If active panel is panel with file items

					wsPortlet.getSearchAndFilterContainer().setVisibleButtonSave(true); //ADDED 24/04/2012

//					wsPortlet.getGxtCardLayoutResultPanel().getToolBarItem().activeAllButtonWithoutGroupView(false); //ADDED 06/02/2013
					
					wsPortlet.getGridGroupContainer().setBorderAsOnSearch(true);

					wsPortlet.getGridGroupContainer().mask(ConstantsExplorer.LOADING,ConstantsExplorer.LOADINGSTYLE);

					appContrExplorer.getRpcWorkspaceService().getItemsBySearchName(textSearch, new AsyncCallback<List<FileGridModel>>() {

						@Override
						public void onFailure(Throwable caught) {
							System.out.println("Failure search RPC");
							new MessageBoxAlert("Error", ConstantsExplorer.SERVER_ERROR + " searching item. " +ConstantsExplorer.TRY_AGAIN, null);
							wsPortlet.getGridGroupContainer().unmask();

						}

						@Override
						public void onSuccess(List<FileGridModel> result) {
							wsPortlet.getGridGroupContainer().updateStore(result);
							wsPortlet.getGridGroupContainer().unmask();
						}
					});
				}				
			}
		});

		eventBus.addHandler(PathElementSelectedEvent.TYPE, new PathElementSelectedEventHandler() {

			@Override
			public void onPathElementSelected(PathElementSelectedEvent event) {
				wsPortlet.getSearchAndFilterContainer().searchCancel(); //cancel search

				if(wsPortlet.getGxtCardLayoutResultPanel().getActivePanel() instanceof GxtItemsPanel){ //If active panel is panel with file items
					AppController.getEventBus().fireEvent(new SearchTextEvent(null));
				}

				doPathElementSelected(event);	
			}

			private void doPathElementSelected(PathElementSelectedEvent event) {
				//				appContrExplorer.selectItemInTree(event.getSourceFile().getIdentifier());

				appContrExplorer.expandFolder(event.getSourceFile().getIdentifier());
			}

		});

		eventBus.addHandler(GridElementUnSelectedEvent.TYPE, new GridElementUnSelectedEventHandler() {

			@Override
			public void onGridElementUnSelected(GridElementUnSelectedEvent event) {
				doElementGridSelected(false, null);
			}
		});


		eventBus.addHandler(AddFolderEvent.TYPE, new AddFolderEventHandler() {

			@Override
			public void onAddItem(AddFolderEvent event) {
				AppControllerExplorer.getEventBus().fireEvent(new AddFolderEvent(event.getFileSourceModel(),event.getParentFileModel()));

			}	

		});

		eventBus.addHandler(SendMessageEvent.TYPE, new SendMessageEventHandler() {

			@Override
			public void onSendMessage(SendMessageEvent sendMessageEvent) {
				doSendMessage(sendMessageEvent.getListFileModelSelected());

			}

			private void doSendMessage(List<FileModel> listFileModelSelected) {
				AppControllerExplorer.getEventBus().fireEvent(new SendMessageEvent(null));
			}
		});


		eventBus.addHandler(FileUploadEvent.TYPE, new FileUploadEventHandler() {

			@Override
			public void onFileUploadEvent(FileUploadEvent fileUploadEvent) {

				AppControllerExplorer.getEventBus().fireEvent(new FileUploadEvent(null,fileUploadEvent.getUploadType()));

			}
		});


		eventBus.addHandler(FileDownloadEvent.TYPE, new FileDownloadEventHandler() {

			@Override
			public void onFileDownloadEvent(FileDownloadEvent fileDownloadEvent) {
				AppControllerExplorer.getEventBus().fireEvent(new FileDownloadEvent(fileDownloadEvent.getItemIdentifier(), fileDownloadEvent.getItemName(), fileDownloadEvent.getDownloadType()));

			}
		});


		eventBus.addHandler(DeleteItemEvent.TYPE, new DeleteItemEventHandler() {

			@Override
			public void onDeleteItem(DeleteItemEvent event) {
				doDeleteItem(event);
			}

			private void doDeleteItem(final DeleteItemEvent event){

				AppControllerExplorer.getEventBus().fireEvent(new DeleteItemEvent(event.getFileTarget()));

			}

		});

		eventBus.addHandler(RenameItemEvent.TYPE, new RenameItemEventHandler() {

			@Override
			public void onRenameItem(RenameItemEvent event) {
				doRenameItem(event);
			}

			public void doRenameItem(final RenameItemEvent event) {

				AppControllerExplorer.getEventBus().fireEvent(new RenameItemEvent(event.getFileTarget()));
			}
		});
	}

	private void doElementGridSelected(boolean isSelected, FileModel target) {

		//		wsPortlet.getToolbarPanelContainer().activeButtonsOnSelect(itemSelected);


		wsPortlet.getGxtCardLayoutResultPanel().getToolBarItem().activeButtonsOnSelect(target, isSelected);


		if(isSelected){
			ArrayList<FileModel> listParents = appContrExplorer.getListParentsByIdentifier(target.getIdentifier());

			setPathInView(listParents); //Set file path in tab panel on current item selected

			
			if(isSearchActive){ 	//COMMENTED 30-01-12 - syncronization only if search is active
			
				wsPortlet.getSearchAndFilterContainer().setSearchActive(true); 
	
				appContrExplorer.searching(true);
	
				appContrExplorer.findItemAndSelectItemInTree(target.getIdentifier());
			}

		}

	}

	private void setPathInView(ArrayList<FileModel> parents){

		//this.wsPortlet.getBasicTabContainer().setLabelPath(path); //Set path in tab view panel

		this.wsPortlet.getToolBarPath().setPath(parents); //Set path in tab view panel
	}

	/**
	 * init method
	 * @param rootPanel
	 */
	public void go(final HasWidgets rootPanel) {
		
		final String searchParameter = Window.Location.getParameter(ConstantsPortlet.GET_SEARCH_PARAMETER);
		final boolean instanceWithGrouping = readCookieWorkspaceGridViewSetting();
		
		System.out.println("Cookie "+ConstantsPortlet.GCUBE_COOKIE_WORKSPACE_GRID_VIEW_SETTING + " return "+instanceWithGrouping);
		
		boolean isSearch = false;
		//		Log.trace("Start Workspace Portlet");
		if (this.appContrExplorer == null){
			this.wsPortlet = new WorskpacePortlet(instanceWithGrouping);
		}
		else{
			
			if(searchParameter!=null && !searchParameter.isEmpty())
				isSearch = true;

			this.wsPortlet = new WorskpacePortlet(this.appContrExplorer.getPanel(true, false, !isSearch), instanceWithGrouping);
			eventBus.fireEvent(new LoadAllScopeEvent()); //LOAD ALL SCOPE EVENT
		}
		
		rootPanel.add(wsPortlet.getBorderLayoutContainer());
		
		//SET TOGGLE BUTTON GRID VIEW
		Scheduler.get().scheduleDeferred(new ScheduledCommand() {
			
			@Override
			public void execute() {
				wsPortlet.getGxtCardLayoutResultPanel().getToolBarItem().toggleGridViewButton(instanceWithGrouping);
			}
		});
		
		//If is SEARCH - fire event search text
		if(searchParameter!=null && !searchParameter.isEmpty())
			Scheduler.get().scheduleDeferred(new ScheduledCommand() {
	
				@Override
				public void execute() {
//					wsPortlet.getGxtCardLayoutResultPanel().getToolBarItem().activeAllButtonWithoutGroupView(false);
					wsPortlet.getSearchAndFilterContainer().searchText(searchParameter);
					
				}
			});
	}


	/**
	 * 
	 * @return true if exists a cookie with msg as true value (or not exists the cookie), false otherwise
	 */
	private boolean readCookieWorkspaceGridViewSetting() {
		
		//get the cookie with name GCBUEWorkspaceGridViewSetting
		String msg = Cookies.getCookie(ConstantsPortlet.GCUBE_COOKIE_WORKSPACE_GRID_VIEW_SETTING);
	 
		//if null, there was no cookie
		if(msg == null){ 
			setCookieGridViewSetting("true");
			return true;
		}
		
		if(msg.compareTo("true")==0)
			return true;
		
		return false;
		
	}

    public static void setCookie(String name, String value, int days) {
 
	    if (value == null) {
	        Cookies.removeCookie(name);
	        return;
	    }
	    
        // Now
        Date expiringDate = new Date();
        // Now + days
        expiringDate.setTime(expiringDate.getTime() + ConstantsPortlet.MILLISECS_PER_DAY * days);
        Cookies.setCookie(name, value, expiringDate);
    }
 
    public static void setCookieGridViewSetting(String value) {
             
            setCookie(ConstantsPortlet.GCUBE_COOKIE_WORKSPACE_GRID_VIEW_SETTING, value, ConstantsPortlet.COOKIE_EXPIRE_DAYS);
    }

	public GxtBorderLayoutPanel getMainPanel(){
		return wsPortlet.getBorderLayoutContainer();
	}

	//	public ExplorerPanel getExplorerPanel() {
	//		return wsPortlet.getExplorerPanel();
	//	}

	public void setSizeAsyncTreePanel(int width, int height) {
		wsPortlet.getExplorerPanel().getAsycTreePanel().setSizeTreePanel(width-17, height-55);
	}

	private void updateStoreByRpc(final FileModel folder){

		wsPortlet.getGridGroupContainer().mask(ConstantsExplorer.LOADING,ConstantsExplorer.LOADINGSTYLE);

		System.out.println("In client new RPC getFolderChildrenForFileGrid "+folder.getName());

		appContrExplorer.getRpcWorkspaceService().getFolderChildrenForFileGrid(folder, new AsyncCallback<List<FileGridModel>>() {

			@Override
			public void onFailure(Throwable caught) {
				new MessageBoxAlert("Error", ConstantsExplorer.SERVER_ERROR + " getting items for grid. " +ConstantsExplorer.TRY_AGAIN, null);
			//	System.out.println(caught);
			//	caught.printStackTrace();
				wsPortlet.getGridGroupContainer().unmask();

			}

			@Override
			public void onSuccess(List<FileGridModel> result) {
				wsPortlet.getGridGroupContainer().setCurrentFolderView(folder); //SET folder as current view

				wsPortlet.getGridGroupContainer().unmask();
				wsPortlet.getGridGroupContainer().updateStore(result);

			}
		});
	}

	public FileModel getSelectedFolder(){

		return this.appContrExplorer.getSelectedFolderInTree();
	}


	/**
	 * Following methods implements SubscriberInterface
	 */

	@Override
	public void addedFolder(String itemIdentifier, FileModel parent) {
		updateStoreByRpc(parent);
	}

	@Override
	public void addedFile(String itemIdentifier, FileModel parent) {
		updateStoreByRpc(parent);
	}

	@Override
	public void selectedItem(FileModel item, ArrayList<FileModel> parents) {

		FileModel currentFolder = wsPortlet.getGridGroupContainer().getCurrentFolderView();

		if(currentFolder!=null){
			
			setPathInView(parents); //set path

			if(wsPortlet.getSearchAndFilterContainer().isSearchActive()){ //ADDED 12-04-12
				wsPortlet.getSearchAndFilterContainer().searchCancel(); //TODO added in 05/04/2012
				AppController.getEventBus().fireEvent(new SearchTextEvent(null));
				wsPortlet.getSearchAndFilterContainer().setSearchActive(false);  
				isSearchActive = false;
				if(item.isDirectory())
					updateStoreByRpc(item);
				else
					updateStoreByRpc(item.getParentFileModel());

				return; 
			}

			if (item.isDirectory())
				updateStoreByRpc(item); //View children of folder
			else{
				String currentIdentifier = currentFolder.getIdentifier(); //Actual id parent

				if(!currentIdentifier.equals(item.getParentFileModel().getIdentifier())) {//Update store only if folder parent is differently
					updateStoreByRpc(item.getParentFileModel()); //View contents of parent folder
				}
			}
		}
		else
			updateStoreByRpc(item); //View children of root
	}

	@Override
	public void expandFolderItem(FolderModel folder) {
		updateStoreByRpc(folder);
	}

	@Override
	public boolean renameItem(String itemIdentifier, String newName, String extension) {
		return wsPortlet.getGridGroupContainer().renameItem(itemIdentifier, newName, extension);

	}

	@Override
	public boolean deleteItem(String itemIdentifier) {
		return wsPortlet.getGridGroupContainer().deleteItem(itemIdentifier);

	}

	@Override
	public void rootLoaded(FileModel root) {
		this.rootIdentifier = root.getIdentifier();	
	}

	@Override
	public void setParentItemSelected(ArrayList<FileModel> listParents){
		setPathInView(listParents);
	}

	@Override
	public void smartFolderSelected(final String folderId, final String category) {


		System.out.println("In client folderId: " + folderId);
		System.out.println("In client category: " + category);

		wsPortlet.getGridGroupContainer().mask(ConstantsExplorer.LOADING,ConstantsExplorer.LOADINGSTYLE);

		wsPortlet.getGridGroupContainer().setBorderAsOnSearch(true);

		if (folderId != null && !folderId.isEmpty()) {

			appContrExplorer.getRpcWorkspaceService().getSmartFolderResultsById(folderId,new AsyncCallback<List<FileGridModel>>() {

				@Override
				public void onFailure(Throwable caught) {
					new MessageBoxAlert("Error", ConstantsExplorer.SERVER_ERROR + " getting smart folders. " +ConstantsExplorer.TRY_AGAIN, null);
					wsPortlet.getGridGroupContainer().unmask();
				}

				@Override
				public void onSuccess(List<FileGridModel> result) {
					wsPortlet.getSearchAndFilterContainer().setSearchActive(true);
					isSearchActive = true;
					wsPortlet.getGridGroupContainer().unmask();
					wsPortlet.getGridGroupContainer().updateStore(result);
				}

			});
		} else {

			if (category != null && !category.isEmpty()) {

				appContrExplorer.getRpcWorkspaceService().getSmartFolderResultsByCategory(category, new AsyncCallback<List<FileGridModel>>() {

					@Override
					public void onFailure(Throwable caught) {
						new MessageBoxAlert("Error", ConstantsExplorer.SERVER_ERROR + " getting smart folder results by category. " +ConstantsExplorer.TRY_AGAIN, null);
					}

					@Override
					public void onSuccess(List<FileGridModel> result) {
						wsPortlet.getGridGroupContainer().unmask();
						wsPortlet.getGridGroupContainer().updateStore(result);
					}
				});

			}

		}

	}

	@Override
	public void movedItems(String sourceParentIdentifier, FileModel targetParent) {
		updateStoreByRpc(targetParent);
	}

	@Override
	public void switchView(ViewSwitchType type){

		if(type.equals(ViewSwitchType.Tree) || type.equals(ViewSwitchType.SmartFolder)){
			wsPortlet.getGxtCardLayoutResultPanel().setActivePanel(ViewSwitchTypeInResult.Group);
			wsPortlet.getSearchAndFilterContainer().setEmptyText(ConstantsPortlet.SEARCHINWORSPACE);
		}
		else{
			wsPortlet.getGxtCardLayoutResultPanel().setActivePanel(ViewSwitchTypeInResult.Messages);
			wsPortlet.getSearchAndFilterContainer().setEmptyText(ConstantsPortlet.SEARCHINMESSAGE);
		}

		//***ADDED 24/04/2012
		wsPortlet.getSearchAndFilterContainer().searchCancel(); 
		eventBus.fireEvent(new SearchTextEvent(null));
		//		appContrExplorer.searching(false);
		//**************

	}

	@Override
	public void refreshFolder(FileModel folderTarget) {
		updateStoreByRpc(folderTarget);

	}

	//	@Override
	//	public void updatePrevieMessage(String fromLogin, String subject,
	//			String date, String body, List<FileModel> attachs) {
	//		wsPortlet.getMessagesPanelContainer().setBodyValue(subject, body);
	//		wsPortlet.getMessagesPanelContainer().setFromTitle(fromLogin, date);
	//		wsPortlet.getMessagesPanelContainer().setAttachs(attachs);
	//		
	//	}

	
	@Override
	public void createNewMessage(final HashMap<String, String> hashAttachs) {
		GWT.runAsync(MailForm.class, new RunAsyncCallback() {
			@Override
			public void onSuccess() {
				if (hashAttachs.size() == 0) { //no attachments
					new MailForm();
				} else {
					new MailForm(hashAttachs);
				}
			}
			public void onFailure(Throwable reason) {
				Window.alert("Could not load this component: " + reason.getMessage());
			}
		});
	}

}
