/*
 * Copyright 2009-2010 Yuichiro Moriguchi
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.morilib.nina.cmd;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.morilib.nina.Nina;
import net.morilib.nina.NinaConsole;
import net.morilib.nina.NinaNullConsole;
import net.morilib.nina.Quadro;
import net.morilib.nina.translate.NinaTranslator;
import net.morilib.nina.translate.NinaTranslatorJavaScript;
import net.morilib.nina.translate.NinaTranslatorXML;
import net.morilib.nina.translate.ProxyNinaTranslator;
import net.morilib.nina.translate.sh.ShNinaRealFile;
import net.morilib.sh.ShFile;
import net.morilib.sh.ShFileSystem;

/**
 *
 *
 * @author MORIGUCHI, Yuichiro 2013/10/23
 */
public class NinatOptions implements NinaInfo {

	private static final Pattern POPT = Pattern.compile("-P([^=]+)=(.*)");
	private static final Pattern TABP = Pattern.compile("--tab=([0-9]+)");

	//
	private NinaTranslator translator = new ProxyNinaTranslator();
	private NinaTranslator report = null;
	private Map<String, String> opts = new HashMap<String, String>();
	private List<String> libs = new ArrayList<String>();
	private NinaConsole console = NinaNullConsole.NULL;
	private boolean jflag = false;
	private boolean stdin = false;

	//
	String filename;

	//
	int parseOptions(String[] args, Map<String, String> prms) {
		int k = 0, x;
		Matcher m;
		String s;

		for(; k < args.length; k++) {
			s = args[k];
			if(s.equals("-J")) {
				jflag = true;
			} else if(s.startsWith("-L")) {
				libs.add(s.substring(2));
			} else if(s.equals("-v")) {
				console = this;
			} else if(s.equals("-i")) {
				translator = new NinaTranslatorJavaScript();
				opts.put("interpret", "on");
			} else if(s.equals("-I")) {
				if(k + 1 < args.length) {
					opts.put("inject", args[++k]);
				}
			} else if(s.equals("-")) {
				stdin = true;
			} else if((m = POPT.matcher(s)).matches()) {
				prms.put(m.group(1), m.group(2));
			} else if(!s.startsWith("--")) {
				return k;
			} else if(s.equals("--help")) {
				usage();
				System.exit(2);
			} else if(s.equals("--lint")) {
				Quadro.errst = System.err;
			} else if(s.startsWith("--libpath=")) {
				libs.add(s.substring(10));
			} else if(s.equals("--verbose")) {
				console = this;
			} else if(s.equals("--xml")) {
				report = new NinaTranslatorXML();
			} else if((m = TABP.matcher(s)).matches()) {
				Quadro.setTab(Integer.valueOf(m.group(1)));
			} else if((x = s.indexOf('=')) < 0) {
				opts.put(s.substring(2), "");
			} else {
				opts.put(s.substring(2, x), s.substring(x + 1));
			}
		}
		return k;
	}

	/**
	 * 
	 * @param p
	 * @param a
	 */
	public void print(String p, Object... a) {
		System.err.println(NinatMessages.getMessage(p, a));
	}

	/**
	 * 
	 * @param p
	 * @param a
	 */
	public void perror(String p, Object... a) {
		System.err.print(NinatMessages.getMessage("errorheader"));
		System.err.println(NinatMessages.getMessage(p, a));
	}

	/**
	 * 
	 * @param p
	 * @param a
	 */
	public void pwarn(String p, Object... a) {
		System.err.print(NinatMessages.getMessage("warnheader"));
		System.err.println(NinatMessages.getMessage(p, a));
	}

	/**
	 * 
	 * @param p
	 * @param a
	 */
	public void pmessage(String p) {
		System.err.print(NinatMessages.getMessage("errorheader"));
		System.err.println(p);
	}

	/**
	 * 
	 */
	public void usage() {
		int l = Integer.parseInt(NinatMessages.getMessage(
				"usage.length"));
		String x;

		print("title", Nina.VERSION);
		for(int i = 1; i <= l; i++) {
			x = String.format("%03d", i);
			print("usage." + x);
		}
	}

	/**
	 * @return the translator
	 */
	public NinaTranslator getTranslator() {
		return translator;
	}

	/**
	 * 
	 * @return
	 */
	public NinaTranslator getReport() {
		return report;
	}

	/* (non-Javadoc)
	 * @see net.morilib.nina.cmd.NinaInfo#getClassName()
	 */
	@Override
	public String getClassName() {
		char[] a;

		a    = getOutputFilename().toCharArray();
		a[0] = Character.toUpperCase(a[0]);
		return new String(a);
	}

	/* (non-Javadoc)
	 * @see net.morilib.nina.cmd.NinaInfo#getBufSize()
	 */
	@Override
	public String getBufSize() {
		String s;

		return (s = getOption("bufsize")).equals("") ? "1024" : s;
	}

	/* (non-Javadoc)
	 * @see net.morilib.nina.cmd.NinaInfo#getFilename()
	 */
	public String getFilename() {
		return filename;
	}

	/* (non-Javadoc)
	 * @see net.morilib.nina.cmd.NinaInfo#getOutputFilename()
	 */
	public String getOutputFilename() {
		String s;

		return (s = getOption("outfile")).equals("") ? filename : s;
	}

	/* (non-Javadoc)
	 * @see net.morilib.nina.cmd.NinaInfo#getOutputDir()
	 */
	@Override
	public Object getOutputDir() {
		String s;

		return new File((s = getOption("output")).equals("") ?
				"." : s);
	}

	/* (non-Javadoc)
	 * @see net.morilib.nina.cmd.NinaInfo#getTitleFile(java.lang.String)
	 */
	public Object getTitleFile(String t) {
		String s;
		char[] a;

		a = (getOutputFilename() + t).toCharArray();
		a[0] = Character.toUpperCase(a[0]);
		s = (s = getOption("output")).equals("") ? "." : s;
		return new File(s, new String(a));
	}

	/* (non-Javadoc)
	 * @see net.morilib.nina.cmd.NinaInfo#getConsole()
	 */
	public NinaConsole getConsole() {
		return console;
	}

	/* (non-Javadoc)
	 * @see net.morilib.nina.cmd.NinaInfo#getInjectFile()
	 */
	@Override
	public Object getInjectFile() {
		String s;

		s = opts.get("inject");
		return s != null ? new File(s) : null;
	}

	/* (non-Javadoc)
	 * @see net.morilib.nina.cmd.NinaInfo#getInputStream(java.lang.String, java.lang.String)
	 */
	@Override
	public OutputStream getOutputStream(Object path,
			String file) throws IOException {
		return new FileOutputStream(new File((File)path, file));
	}

	/* (non-Javadoc)
	 * @see net.morilib.nina.cmd.NinaInfo#getInputStream(java.lang.String, java.lang.String)
	 */
	@Override
	public OutputStream getOutputStream(
			Object file) throws IOException {
		return new FileOutputStream((File)file);
	}

	/* (non-Javadoc)
	 * @see net.morilib.nina.cmd.NinaInfo#getOutputStream(java.lang.Object, java.lang.String)
	 */
	@Override
	public InputStream getInputStream(Object path,
			String file) throws IOException {
		return new FileInputStream(new File((File)path, file));
	}

	/* (non-Javadoc)
	 * @see net.morilib.nina.cmd.NinaInfo#getOutputStream(java.lang.Object)
	 */
	@Override
	public InputStream getInputStream(
			Object file) throws IOException {
		return new FileInputStream((File)file);
	}

	/* (non-Javadoc)
	 * @see net.morilib.nina.cmd.NinaInfo#postprocess()
	 */
	@Override
	public void postprocess() {
	}

	/* (non-Javadoc)
	 * @see net.morilib.nina.cmd.NinaInfo#getShOutputDir()
	 */
	@Override
	public ShFile getShOutputDir(ShFileSystem fs) {
		return new ShNinaRealFile(fs, "/output", (File)getOutputDir());
	}

	/* (non-Javadoc)
	 * @see net.morilib.nina.cmd.NinaInfo#getShOutputFile(net.morilib.sh.ShFileSystem, java.lang.String, java.lang.String)
	 */
	@Override
	public ShFile getShOutputFile(ShFileSystem fs, String p,
			String f) {
		return new ShNinaRealFile(fs, p,
				new File((File)getOutputDir(), f));
	}

	/**
	 * 
	 * @param key
	 * @return
	 */
	public String getOption(String key) {
		String s;

		return (s = opts.get(key)) != null ? s : "";
	}

	/**
	 * 
	 * @param key
	 * @return
	 */
	public boolean isOptionDefined(String key) {
		return opts.containsKey(key);
	}

	/**
	 * 
	 * @return
	 */
	public List<String> getLibraryList() {
		return Collections.unmodifiableList(libs);
	}

	/**
	 * 
	 * @return
	 */
	public String getJavaFile() {
		return getTitleFile(".java").toString();
	}

	/**
	 * 
	 * @return
	 */
	public boolean isJavaCompiler() {
		return jflag;
	}

	/**
	 * 
	 * @return
	 */
	public boolean isStandardInput() {
		return stdin;
	}

}
