package com.interpress_project.modernshare.client.controller.command;

import java.util.Calendar;
import java.util.Locale;
import java.util.Timer;

import com.interpress_project.modernshare.client.controller.model.PropertyManager;
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;
import com.interpress_project.modernshare.ipcommon.SystemBase;

/**
 * Represents a singleton.
 * @stereotype Singleton factory
 */

public class TaskManager {
	/**
	 * @stereotype creates
	 */
	/*#com.interpress_project.modernshare.client.controller.command.TaskWorkerThread Dependency20*/

	private final SystemBase sb = SystemBase.getInstance();
	private final PropertyManager propmgr = PropertyManager.getInstance();
	private final LogEventSource logEventSource = LogEventSource.getInstance();
	private Timer theTimer = null;

	/**
	 * Holds singleton instance
	 */
	private static TaskManager instance;

	/**
	 * prevents instantiation
	 */
	private TaskManager() {
		logEventSource.addEventListener(ViewManager.getInstance());
	}

	/**
	 * Returns the singleton instance.
	 @return	the singleton instance
	 */
	static public TaskManager getInstance() {
		if (instance == null) {
			instance = new TaskManager();
		}
		return instance;
	}

	/**
	 * start
	 */
	public void start() {
		sb.getLogger().debug("TaskManager started.");
	}

	/**
	 * stop
	 */
	public void stop() {
		if (theTimer != null) {
			theTimer.cancel();
			theTimer = null;
			sb.getLogger().debug("TaskManager stopped.");
		}
	}

	/**
	 * updateSchedule
	 */
	public void updateSchedule(String path) {
		if (theTimer != null) {
			theTimer.cancel();
			theTimer = null;
		}
		sb.getLogger().debug("Timer schedule for " + path);		
		theTimer = new Timer();

		Calendar cal = Calendar.getInstance(Locale.JAPAN);
		int duration = propmgr.getDuration();
		cal.add(Calendar.MINUTE, duration);
		theTimer.schedule(new TaskWorkerThread(), cal.getTime());
		String msg = "ホットショットフォルダの同期が" + cal.getTime() + "にスケジュールされました。";
		logEventSource.fireEvent(new LogEvent(this, msg, LogEventType.INFO));
	}

	/**
	 * dispose
	 */
	public void dispose() {
		stop();
		logEventSource.removeEventListener(ViewManager.getInstance());
		sb.getLogger().debug("TaskManager disposed.");
	}
}
