/**
 *
 */
package com.fp.hbm.bgenerator.xml;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;

import com.fp.hbm.bgenerator.AbstractColumn;
import com.fp.hbm.bgenerator.AbstractMapper;
import com.fp.hbm.bgenerator.Reference;
import com.fp.common.exception.APPException;

/**
 * @author German Fiallos 
 *
 */
public class Mapper extends AbstractMapper {

	public static ResourceBundle paramResource = null;

	private String versioncontrol = null;

	private String transportBean = null;

	private String transportId = null;

	public Mapper() {
		if (paramResource == null) {
			paramResource = ResourceBundle.getBundle("cfg");
		}
		this.packageName = packageBase + ".";
		this.versioncontrol = paramResource.getString("vesion.control.field").toUpperCase();
		this.transportBean = paramResource.getString("transport.bean.single.class");
		this.transportId = paramResource.getString("transport.bean.id.single.class");
	}

	public String getXMLMapping() throws APPException {
		StringWriter sw = new StringWriter();
		PrintWriter pw = new PrintWriter(sw);
		pw.println("<?xml version='1.0' encoding='UTF-8'?>");
		pw
				.println("<!DOCTYPE hibernate-mapping PUBLIC '-//Hibernate/Hibernate Mapping DTD 3.0//EN' 'http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd' >");
		pw.println("<hibernate-mapping package='" + this.packageName + "' auto-import='"
				+ ((this.ent.getAutoimport().compareTo("1") != 0) ? "false" : "true") + "'>");
		// + "dynamic-update='true' >");
		pw.println("<class name='" + this.entity + "' table='" + this.table + "' " + ">");
		this.formatKey(pw);
		if (this.optimistic) {
			pw.println("<!-- OPTIMISTIC LOCKING-->");
			pw.println("<version name='" + versioncontrol.toLowerCase() + "' column='" + versioncontrol.toUpperCase() + "'/>");
		}
		this.formatColumns(pw);
		this.formatXMLReferences(pw);
		/*
		if (this.ent.getInsertdml() != null) {
			pw.print("<sql-insert>");
			pw.print(this.ent.getInsertdml());
			pw.print("</sql-insert>");
		}
		if (this.ent.getUpdatedml() != null) {
			pw.print("<sql-update>");
			pw.print(this.ent.getUpdatedml());
			pw.print("</sql-update>");
		}
		*/
		pw.println("</class>");
		pw.println("</hibernate-mapping>");
		String data = sw.toString();
		pw.close();
		return data;
	}

	public String getKeyClassData() throws APPException {
		StringWriter sw = new StringWriter();
		PrintWriter pw = new PrintWriter(sw);
		pw.println("package " + this.packageName + ";");
		this.formatKeyImports(pw);
		pw.println("/**Clase que hace referencia a la Clave Primaria de " + this.table + "*/");
		pw.println("public class " + this.entity + "Key " + " extends com.fp.dto.AbstractDataTransport" 
				+ "  implements Serializable,Cloneable," + transportId + ((this.history) ? ",History" : "") + "{");
		this.formatBasicsJava(pw);
		this.formatKeyJava(pw);
		this.createKeyConstructor(pw);
		this.formatKeyJavaGS(pw);
		this.formatKeyEquals(pw);
		this.formatKeyHash(pw);
		formatKeyClone(pw);
		this.formatToString(pw, "pk");
		if (this.history) {
			this.formatKeyHistoryNeededMethods(pw);
		}
		pw.println("}");
		String data = sw.toString();
		pw.close();
		return data;
	}

	private void formatClassPKData(PrintWriter pw) throws APPException {
		pw.println("/**");
		pw.println("* Clave primaria de la Entidad " + this.entity);
		pw.println("*/");
		if (this.isKeyClassNeeded()) {
			pw.println("private " + this.getKeyClasss() + " pk;");
		} else {
			pw.println("private " + this.primary.get(0).getJavaSimple() + " pk;");
		}
	}

	private void formatClassPKDataGS(PrintWriter pw) throws APPException {
		String className = "";
		if (this.isKeyClassNeeded()) {
			className = this.getKeyClasss();
		} else {
			className = this.primary.get(0).getJavaSimple();
		}
		pw.println("/**Entrega la Clave primaria de " + this.entity);
		pw.println("@return El objeto que referencia a la Clave primaria de " + this.entity);
		pw.println("*/");
		pw.println("public " + className + " getPk(){");
		pw.println("  return pk;");
		pw.println("}");
		pw.println("/**Fija un nuevo valor a la Clave primaria de " + this.entity);
		pw.println("@param pPk El objeto que referencia a la nueva Clave primaria de " + this.entity);
		pw.println("*/");
		pw.println("public void setPk(" + className + " pPk){");
		pw.println("  pk=pPk;");
		pw.println("}");
	}

	public String getClassData() throws APPException {
		StringWriter sw = new StringWriter();
		PrintWriter pw = new PrintWriter(sw);
		pw.println("package " + this.packageName + ";");
		this.formatClassImports(pw);
		String ext = "";
		if (this.history) {
			// ext = " extends AbstractExpire ";
		}
		pw.println("/**Clase que implementa la entidad de Hibernate que hace referencia a la tabla " + this.table + "*/");
		pw.println("public class " + this.entity + ((this.sExtends == null) ? ext : " extends " + this.sExtends) + " implements Serializable,"
				+ this.transportBean + ",Cloneable" + ((this.sImplements == null) ? "" : "," + this.sImplements) + "{");
		this.formatBasicsJava(pw);
		this.formatClassPKData(pw);
		this.formatColumnsJava(pw);
		this.createClassConstructor(pw);
		this.formatClassPKDataGS(pw);
		this.formatColumnsJavaGS(pw);
		this.formatClassCompare(pw);
		this.formatClassHash(pw);
		this.formatToString(pw, "");
		this.formatJavaReferences(pw);
		this.formatCreateInstance(pw);
		formatClassCloneable(pw);
		if (this.history) {
			this.formatHistoryNeededMethods(pw);
		}
		pw.println("}");
		String data = sw.toString();
		pw.close();
		return data;
	}

	protected void formatJavaReferences(PrintWriter pw) {
		if (this.references != null) {
			for (Reference ref : this.references) {
				pw.println(ref.getJava());
			}
		}
	}

	private void formatColumnsJava(PrintWriter pw) throws APPException {
		for (AbstractColumn col : this.columns) {
			pw.println(col.formatJava());
		}
	}

	private void formatClassImports(PrintWriter pw) throws APPException {
		Map<String, String> m = new HashMap<String, String>();
		m.put("import java.io.Serializable;", "");
		m.put("import java.lang.reflect.Field;", "");
		if (this.references != null && this.references.size() > 0) {
			for (Reference imp : this.references) {
				List<String> lImp = imp.getImport();
				for (String string : lImp) {
					m.put(string, "");
				}
			}
		}
		String cTransportBean = paramResource.getString("transport.bean.class");
		m.put("import " + cTransportBean + ";", "");
		if (this.history) {
			//m.put("import com.fp.dto.hb.AbstractExpire;", "");
		}
		for (AbstractColumn col : this.columns) {
			List<String> im = col.getImportData();
			for (String dt : im) {
				m.put("import " + dt + ";", "");
			}
		}

		for (AbstractColumn col : this.primary) {
			List<String> im = col.getImportData();
			for (String dt : im) {
				m.put("import " + dt + ";", "");
			}
		}
		pw.println();
		for (String imp : m.keySet()) {
			pw.println(imp);
		}
		pw.println();
	}

	private void formatKeyImports(PrintWriter pw) throws APPException {
		Map<String, String> m = new HashMap<String, String>();
		m.put("import java.io.Serializable;", "");
		m.put("import java.lang.reflect.Field;", "");
		String cTransportBean = paramResource.getString("transport.bean.id.class");
		m.put("import " + cTransportBean + ";", "");
		if (this.history) {
			//m.put("import com.fp.dto.hb.AbstractExpire;", "");
			m.put("import com.fp.dto.hb.History;", "");
		}
		for (AbstractColumn col : this.primary) {
			List<String> im = col.getImportData();
			for (String dt : im) {
				m.put("import " + dt + ";", "");
			}
		}
		pw.println();
		for (String imp : m.keySet()) {
			pw.println(imp);
		}
		pw.println();
	}

	private void formatColumnsJavaGS(PrintWriter pw) throws APPException {
		for (AbstractColumn col : this.columns) {
			pw.println(col.formatJavaGetSet(false));
		}

	}

	private void formatKeyJava(PrintWriter pw) throws APPException {
		for (AbstractColumn col : this.primary) {
			pw.println(col.formatJava());
		}

	}

	private void formatKeyJavaGS(PrintWriter pw) throws APPException {
		for (AbstractColumn col : this.primary) {
			pw.println(col.formatJavaGetSet(true));
		}

	}

	private void formatKey(PrintWriter pw) throws APPException {
		if (this.isKeyClassNeeded()) {
			pw.println("<composite-id name='pk' class='" + this.entity + "Key'>");
			for (AbstractColumn mc : this.primary) {
				pw.println("\t" + mc.formatComposeKey());
			}
			pw.println("</composite-id>");
		} else {
			if (this.primary.size() < 1) {
				throw new APPException("HM001", "Tabla " + this.table + " no tiene clave primaria");
			}
			this.primary.get(0).formatSinglePK(pw);

		}
	}

	private void formatColumns(PrintWriter pw) throws APPException {
		for (AbstractColumn col : this.columns) {
			if (this.optimistic) {
				if (col.getName().toUpperCase().compareTo(versioncontrol) == 0) {
					continue;
				}
			}
			pw.println("\t" + col.formatProperty());
		}
	}

	private void formatXMLReferences(PrintWriter pw) throws APPException {
		if (references != null) {
			for (Reference ref : this.references) {
				pw.println("\t" + ref.getXML());
			}
		}
	}

	@Override
	public void safeEntity() throws IOException, APPException {
		String sPath = this.parent.getPath() + "/" + this.ent.getProject() + "/src/main" + this.parent.getXmlPath()
				+ getPackageName().replaceAll("\\.", "/");
		this.safe(getXMLMapping(), sPath, getEntity() + ".hbm.xml");
		sPath = this.parent.getPath() + "/" + this.ent.getProject() + "/src/main" + this.parent.getSoucePath()
				+ getPackageName().replaceAll("\\.", "/");
		if (isKeyClassNeeded()) {
			this.safe(getKeyClassData(), sPath, getEntity() + "Key.java");
		}
		this.safe(getClassData(), sPath, getEntity() + ".java");

	}

}
