/**
 * 
 */
package org.gcube.portlets.user.reportgenerator.client.targets;




import java.util.List;

import org.gcube.portlets.user.workspace.client.interfaces.GXTFolderItemTypeEnum;
import org.gcube.portlets.user.workspace.client.model.FileModel;

import com.extjs.gxt.ui.client.dnd.DND.Operation;
import com.extjs.gxt.ui.client.dnd.DropTarget;
import com.extjs.gxt.ui.client.dnd.Insert;
import com.extjs.gxt.ui.client.event.DNDEvent;
import com.extjs.gxt.ui.client.store.TreeStoreModel;
import com.extjs.gxt.ui.client.widget.treepanel.TreePanel;
import com.google.gwt.core.client.GWT;

/**
 * @author Federico De Faveri defaveri@isti.cnr.it
 *
 */
public class DropTSListener extends DropTarget {
	/**
	 * 
	 */
	public static final String NO_DROP = "x-dd-drop-nodrop";
	/**
	 * 
	 */
	public static final String OK_DROP = "x-dd-drop-ok";
	/**
	 * 
	 */
	public static final String OK_DROP_ADD = "x-dd-drop-ok-add";

	protected TSArea panel;

	/**
	 * 
	 * @param panel .
	 * @param config .
	 */
	public DropTSListener(TSArea panel) {
		super(panel);
		this.panel = panel;
		//IMPORTANT
		setOperation(Operation.COPY);
	}

	@Override
	protected void showFeedback(DNDEvent event) {
		if (!isValidDropTarget(event)) {
			Insert.get().hide();
			event.getStatus().setStatus(false);
			return;
		}
		super.showFeedback(event);
	}


	@SuppressWarnings("unchecked")
	private boolean isValidDropTarget(DNDEvent event) {
		GWT.log("isValidDropTarget");
		TreePanel<FileModel> source = (TreePanel<FileModel>) event.getDragSource().getComponent();
		List<FileModel> selection = source.getSelectionModel().getSelection();

		for (FileModel model : selection) {
			GWT.log("selection: " + model.getGXTFolderItemType());
			if(model.getGXTFolderItemType()!=null){
				if (model.getGXTFolderItemType().equals(GXTFolderItemTypeEnum.TIME_SERIES)) 
					return true;
			}
		}
		return false;
	}
	
	/**
	 * @param source .
	 * @param e .
	 * @param data .
	 * @return .
	 */
	protected void onDragDrop(DNDEvent event) {   
		
		   super.onDragDrop(event); 

			if(event.getData() != null){				
				List<TreeStoreModel> listItemsSource =  event.getData();
				GWT.log("Number of move " + listItemsSource.size());
				
				FileModel sourceFileModel = null; //for print
				
				for(TreeStoreModel itemSource : listItemsSource){

					sourceFileModel = (FileModel) itemSource.getModel();

					if(sourceFileModel.getParentFileModel()!=null)
						GWT.log("Source Name " + sourceFileModel.getName() + " id " + sourceFileModel.getIdentifier() + " end drag " + " Parent Name: " + sourceFileModel.getParentFileModel().getName() + "id " + sourceFileModel.getParentFileModel().getIdentifier());
					else
						GWT.log("Source Name " + sourceFileModel.getName() + " id " + sourceFileModel.getIdentifier() + " end drag ");
					
					GWT.log("Child count: " + itemSource.getChildCount());
					
					panel.fetchTS(sourceFileModel.getIdentifier(), false , true);
					
				}
			}
	
	}

}
