package com.interpress_project.modernshare.client.view.remotefs;

import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.Viewer;

import com.interpress_project.modernshare.client.controller.delegate.exceptions.InternalFailException;
import com.interpress_project.modernshare.client.controller.model.ISVNFileItem;
import com.interpress_project.modernshare.client.events.LogEvent;
import com.interpress_project.modernshare.client.events.LogEventSource;
import com.interpress_project.modernshare.client.events.LogEventType;
import com.interpress_project.modernshare.client.view.ViewManager;

public class RemoteFileTreeContentProvider implements ITreeContentProvider {
	protected ViewManager vmgr = ViewManager.getInstance();
	protected LogEventSource logEventSource = LogEventSource.getInstance();

	/**
	 * getChildren
	 * @param element Object
	 * @return Object[]
	 */
	public Object[] getChildren(Object element) {
		/**
		 * 画面更新の処理はDisplay.syncExec()で実行する。(Commandキューを利用すると、データ更新処理などが
		 * 混雑した場合に、すぐに実行されないため。)
		 */
		GetSVNItemsWorker worker = new GetSVNItemsWorker((ISVNFileItem) element);
		vmgr.getShell().getDisplay().syncExec(worker);
		return worker.getKids();
	}

	/**
	 * getElements
	 * @param element Object
	 * @return Object[]
	 */
	public Object[] getElements(Object element) {
		return getChildren(element);
	}

	/**
	 * hasChildren
	 * @param element Object
	 * @return boolean
	 */
	public boolean hasChildren(Object element) {
		return getChildren(element).length > 0;
	}

	/**
	 * getParent
	 * @param element Object
	 * @return Object
	 */
	public Object getParent(Object element) {
		return null;
	}

	/**
	 * dispose
	 */
	public void dispose() {
	}

	/**
	 * inputChanged
	 * @param viewer Viewer
	 * @param old_input Object
	 * @param new_input Object
	 */
	public void inputChanged(Viewer viewer, Object old_input, Object new_input) {
	}

	/**
	 * GetSVNItemsWorker
	 * @author ys
	 */
	private class GetSVNItemsWorker implements Runnable {
		private ISVNFileItem fileItem;
		private Object[] kids = null;

		/**
		 * GetSVNItemsWorker
		 * @param fileItem
		 */
		public GetSVNItemsWorker(ISVNFileItem fileItem) {
			this.fileItem = fileItem;
		}

		/**
		 * run
		 */
		public void run() {
			try {
				kids = ((ISVNFileItem) fileItem).getSVNItems();
			}
			catch (InternalFailException ex) {
				logEventSource.fireEvent(new LogEvent(this, ex.getMessage(), LogEventType.ERROR,ex));
			}
		}

		/**
		 * getKids
		 * @return
		 */
		public Object[] getKids() {
			return kids == null ? new Object[0] : kids;
		}
	}
}
