package jp.hasc.hasctool.ui.commands;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import jp.hasc.hasctool.core.data.LabelInfo;
import jp.hasc.hasctool.core.runtime.RuntimeContext;
import jp.hasc.hasctool.core.util.CoreUtil;
import jp.hasc.hasctool.ui.util.UIUtil;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.InputDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.handlers.HandlerUtil;

/**
 * CSVファイルに関連づけられたLabelファイルを新規作成するコマンドです
 * @author iwasaki
 */
public class NewLabelFileFromCSVCommand extends AbstractHandler {
	/** logger for this class */
	private final static org.apache.commons.logging.Log LOG = org.apache.commons.logging.LogFactory
			.getLog(NewLabelFileFromCSVCommand.class);
			
	public static final String ID = "jp.hasc.hasctool.ui.commands.NewLabelFileFromCSVCommand"; //$NON-NLS-1$

	@SuppressWarnings("unchecked")
	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		// Navigator上での選択されたファイルを列挙
		try{
			ISelection selection = HandlerUtil.getCurrentSelection(event);
			if (selection instanceof StructuredSelection) {
				StructuredSelection ss = (StructuredSelection) selection;
				for (Iterator<Object> it = ss.iterator(); it.hasNext();) {
					Object item = it.next();
					if (item instanceof IFile) {
						IFile f=(IFile)item;
						processFile(f, event);
						return null;
					}
				}
			}
			UIUtil.showMessageDialog(HandlerUtil.getActiveShell(event), Messages.NewLabelFileFromCSVCommand_SelectCSVFile);
		}catch(Exception ex) {
			LOG.warn("Exception",ex); //$NON-NLS-1$
			UIUtil.showMessageDialog(HandlerUtil.getActiveShell(event),"[Exception]\n"+ex.toString()); //$NON-NLS-1$
		}
		return null;
	}
	
	Pattern PAT_BASENAME = Pattern.compile("(.+)-[a-zA-Z0-9_]+\\.csv");

	private void processFile(IFile f, ExecutionEvent event) throws CoreException{
		IWorkbenchWindow win = HandlerUtil.getActiveWorkbenchWindow(event);
		//UIUtil.showMessageDialog(win.getShell(), f.getName());
		String fpath=f.getFullPath().toString();
		String lpath=CoreUtil.changeFileExt(fpath, ".label"); //$NON-NLS-1$
		InputDialog dlg=new InputDialog(win.getShell(), Messages.NewLabelFileFromCSVCommand_NewLabelFile, 
				Messages.NewLabelFileFromCSVCommand_InputLabelFilePath, lpath, null);
		if (dlg.open()!=Dialog.OK) return;
		lpath=dlg.getValue();
		IFile lf = f.getWorkspace().getRoot().getFile(new Path(lpath));
		if (lf.exists()) {
			if (!MessageDialog.openConfirm(win.getShell(), Messages.NewLabelFileFromCSVCommand_Overwrite, Messages.NewLabelFileFromCSVCommand_OverwriteOK+"\n"+lpath)) {
				return;
			}
		}
		//
		String ppath=lf.getProject().getFullPath().toString();
		String fpathraw=fpath;
		if (fpath.startsWith(ppath)) {
			fpath=ResourceStreamProvider.KEYWORD_PROJECT_ROOT+fpath.substring(ppath.length());
		}
		// targetfile header
		String contents=LabelInfo.HEADER_PREFIX_TARGET_FILE+fpath+"\n"; //$NON-NLS-1$
		// audiofile header
		Matcher m = PAT_BASENAME.matcher(fpathraw);
		if (m.matches()) {
			String basepath=m.group(1);
			String audiopath=basepath+"-audio.wav";
			IFile audiof = f.getWorkspace().getRoot().getFile(new Path(audiopath));
			if (audiof.exists()) {
				if (audiopath.startsWith(ppath)) {
					audiopath=ResourceStreamProvider.KEYWORD_PROJECT_ROOT+audiopath.substring(ppath.length());
				}
				contents+="#audiofile:"+audiopath+"; offsettime:0.0\n";
			}
		}
		//
		InputStream source=new ByteArrayInputStream(contents.getBytes(RuntimeContext.DEFAULT_CHARSET));
		if (lf.exists()) {
			lf.setContents(source, true,false,null);
		}else{
			lf.create(source, true,null);
		}
		UIUtil.showMessageDialog(win.getShell(), String.format(Messages.NewLabelFileFromCSVCommand_Created,lpath));
		
	}

}
