package jp.co.headwaters.webappos.generator.web;

import java.io.File;

import jp.co.headwaters.webappos.controller.ControllerConstants;
import jp.co.headwaters.webappos.controller.utils.ControllerUtils;
import jp.co.headwaters.webappos.generator.GeneratorConstants;
import jp.co.headwaters.webappos.generator.utils.FileUtils;
import jp.co.headwaters.webappos.generator.utils.GeneratorUtils;
import jp.co.headwaters.webappos.generator.utils.MessageUtils;
import jp.co.headwaters.webappos.generator.utils.PropertyUtils;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.mybatis.generator.api.dom.OutputUtilities;

public class PropertyGenerator {

	private static final Log _logger = LogFactory.getLog(PropertyGenerator.class);

	public static boolean generate(String contextName, String rootPackage) {
		try {
			File outputFile = getOutputFile();
			FileUtils.writeFile(outputFile, getContent(contextName, rootPackage), GeneratorConstants.OUTPUT_PROPERTY_FILE_ENCODING);
		} catch (Exception e) {
			_logger.error(MessageUtils.getString("err.300"), e); //$NON-NLS-1$
			return false;
		}
		return true;
	}

	private static File getOutputFile() {
		StringBuilder sb = new StringBuilder();
		sb.append(GeneratorUtils.getOutputPropertyPath());
		sb.append(ControllerConstants.PROPERTY_FILE_NAME);
		return new File(sb.toString());
	}

	public static String getContent(String contextName, String rootPackage) {
		StringBuilder sb = new StringBuilder();

		// comment
		sb.append("# for "); //$NON-NLS-1$
		sb.append(contextName);
		sb.append(" properties"); //$NON-NLS-1$
		OutputUtilities.newLine(sb);
		OutputUtilities.newLine(sb);

		// package
		sb.append(ControllerConstants.PROPERTY_KEY_ROOT_PACKAGE);
		sb.append("="); //$NON-NLS-1$
		sb.append(rootPackage);
		OutputUtilities.newLine(sb);

		// context
		sb.append(ControllerConstants.PROPERTY_KEY_CONTEXT_NAME);
		sb.append("="); //$NON-NLS-1$
		sb.append(contextName);
		OutputUtilities.newLine(sb);

		// webapps path
		sb.append(ControllerConstants.PROPERTY_KEY_WEBAPPS_PATH);
		sb.append("="); //$NON-NLS-1$
		sb.append(PropertyUtils.getProperty(GeneratorConstants.PROPERTY_KEY_WEBAPPS_PATH));
		if (!sb.toString().endsWith(ControllerUtils.getFileSparator())) {
			sb.append(ControllerUtils.getFileSparator());
		}
		sb.append(contextName);
		sb.append(ControllerUtils.getFileSparator());
		sb.append(GeneratorConstants.WEBAPPS_DIR);
		sb.append(ControllerUtils.getFileSparator());
		OutputUtilities.newLine(sb);

		return sb.toString().replaceAll("\\\\", "\\\\\\\\"); //$NON-NLS-1$ //$NON-NLS-2$
	}
}
