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

import org.eclipse.jface.viewers.IStructuredContentProvider;
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.GUIEvent;
import com.interpress_project.modernshare.client.events.GUIEventSource;
import com.interpress_project.modernshare.client.events.GUIEventType;
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 RemoteFileTableContentProvider implements IStructuredContentProvider {
	protected ViewManager vmgr = ViewManager.getInstance();
	protected LogEventSource logEventSource = LogEventSource.getInstance();
	protected GUIEventSource guiEventSource = GUIEventSource.getInstance();

	/**
	 * getElements
	 * @param element Object
	 * @return Object[]
	 */
	public Object[] getElements(Object element) {
		/**
		 * 画面更新の処理はDisplay.syncExec()で実行する。(Commandキューを利用すると、データ更新処理などが
		 * 混雑した場合に、すぐに実行されないため。)
		 */
		try {
			guiEventSource.fireEvent(new GUIEvent(this, GUIEventType.START));

			GetRevisionWorker worker = new GetRevisionWorker((ISVNFileItem) element);
			vmgr.getShell().getDisplay().syncExec(worker);
			return worker.getKids();
		}
		finally {
			guiEventSource.fireEvent(new GUIEvent(this, GUIEventType.FINISH));
		}
	}

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

	/**
	 * inputChanged
	 * @param viewer Viewer
	 * @param old_object Object
	 * @param new_object Object
	 */
	public void inputChanged(Viewer viewer, Object old_object, Object new_object) {
	}

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

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

		/**
		 * run	
		 */
		public void run() {
			try {
				kids = ((ISVNFileItem) fileItem).getRevisionInfo();
			}
			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;
		}
	}
}
