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

import com.interpress_project.modernshare.client.controller.command.SVNCommandFactory;
import com.interpress_project.modernshare.client.controller.command.SVNCommandManager;
import com.interpress_project.modernshare.client.controller.command.TaskManager;
import com.interpress_project.modernshare.client.controller.command.exceptions.CommandException;
import com.interpress_project.modernshare.client.controller.model.LocalRoot;
import com.interpress_project.modernshare.client.events.LogEvent;
import com.interpress_project.modernshare.client.events.LogEventType;
import com.interpress_project.modernshare.client.view.ViewManager;
import com.interpress_project.modernshare.ipcommon.SystemBase;

/**
 * @stereotype action
 */
public class SyncDataAction extends ActionAdaptor {
	private final SystemBase sb = SystemBase.getInstance();
	private final ViewManager vmgr;
	private final SVNCommandManager cmdmgr = SVNCommandManager.getInstance();
	private final SVNCommandFactory factory = SVNCommandFactory.getInstance();
	private LocalRoot localRoot = null;

	/**
	 * SyncDataAction
	 * @param vmgr
	 * @param item
	 */
	public SyncDataAction(final ViewManager vmgr, LocalRoot localRoot) {
		setText("データの強制同期(&C)");
		setToolTipText("HotShotフォルダとデータセンタ間で強制同期を行います。");
		try {
			setImageDescriptor(ImageFactory.getInstance().getImageDescriptor("sync"));
		}
		catch (Exception ex) {
			sb.getLogger().fatal("リソース設定のエラーが発生しました。", ex);
			System.exit(-1);
		}
		this.vmgr = vmgr;
		this.localRoot = localRoot;
	}

	/**
	 * run
	 */
	public void run() {
		TaskManager taskmgr = TaskManager.getInstance();
		int mode = -1;

		try {
			taskmgr.stop();

			boolean bResult = vmgr.getDialogManager().createYesNoMessageDialog("データの同期確認",
			  "ホットショットフォルダ" + localRoot.getAbsolutePath() + "に対する同期処理を行います。");
			if (bResult == false) {
				return;
			}

			if (localRoot.getPc2host()) {
				mode = vmgr.getDialogManager().createSyncModeDialog();
				if (mode == -1) { // Selected CANCEL.
					return;
				}
			}
			else {
				mode = 1; // ノードがHost2Pcであれば同期はRemote->PCのみ。ダイアログ不要。
			}

			/**
			 * ローカルターゲットリストを同期
			 */
			cmdmgr.execCommand(factory.createSyncListCommand());

			switch (mode) {
				default: {
					return;
				}
				case 0: { // PC -> Remote
					sb.getLogger().debug("PC->Remote: ローカルでリモートを更新");
					cmdmgr.execCommand(factory.createSyncRemoteWithLocalCommand(localRoot));
					break;
				}
				case 1: { // Remote -> PC
					sb.getLogger().debug("Remote->PC: リモートでローカルを更新");
					cmdmgr.execCommand(factory.createSyncLocalWithRemoteCommand(localRoot));
					break;
				}
			}
		}
		catch (CommandException ex) {
			String msg = ex.getCause().getMessage();
			logEventSource.fireEvent(new LogEvent(this, msg, LogEventType.ERROR, ex));
			vmgr.getDialogManager().createErrorMessageDialog(msg);
		}
		finally {
			taskmgr.start();
		}
	}
}
