/*
 * 作成日: 2008/08/05
 * 著作権: Copyright (c) 2005 ZIGEN
 * ライセンス：Eclipse Public License - v 1.0
 * 原文：http://www.eclipse.org/legal/epl-v10.html
 */
package zigen.plugin.db.ext.s2jdbc.entity;

import java.sql.Types;

import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;

import zigen.plugin.db.ext.s2jdbc.entity.rule.DefaultEntityMappingFactory;
import zigen.plugin.db.ext.s2jdbc.entity.rule.IEntityMappingFactory;
import zigen.plugin.db.ext.s2jdbc.util.CodeCreatorUtil;
import zigen.plugin.db.ext.s2jdbc.util.PropertyNameUtil;
import zigen.plugin.db.ui.internal.Column;
import zigen.plugin.db.ui.internal.TreeLeaf;

public class GenerateEntityAction2 extends GenerateEntityAction {

    @Override
    protected void createTypeMembers(IType type, ImportsManager imports, SubProgressMonitor monitor) throws JavaModelException {
        monitor.setTaskName("Create Entity");
        //		imports.addImport("javax.persistence.Entity"); //$NON-NLS-1$
        // プロパティフィールドの作成
        createField(type, imports, monitor);
        // super.createTypeMembers(type, imports, monitor);
        StringBuffer buf = new StringBuffer();
        // do_toString(buf);
        // type.createMethod(buf.toString(), null, false, null);
        if (monitor != null)
            monitor.done();
    }

    protected String constructCUContent(ICompilationUnit cu, String typeContent, String lineDelimiter) throws CoreException {
        StringBuffer sb = new StringBuffer();
        sb.append("/**").append("\r\n");
        sb.append(" * ").append(entity.getLabel()).append("\r\n");
        sb.append(" *").append("\r\n");
        sb.append(" */");

        String typeComment = sb.toString();
        IPackageFragment pack = (IPackageFragment) cu.getParent();
        StringBuffer buf = new StringBuffer();
        if (!pack.isDefaultPackage())
            buf.append("package ").append(pack.getElementName()).append(';'); //$NON-NLS-1$
        buf.append(lineDelimiter).append(lineDelimiter);
        if (typeComment != null)
            buf.append(typeComment).append(lineDelimiter);
        // Entityアノテーションを追加
        // テーブル名は小文字にすること

        // スキーマ付きのテーブル名
        String anotation = "@Table(name = \"" + entity.getSqlTableName() + "\")"; //$NON-NLS-1$ //$NON-NLS-2$

        buf.append(anotation).append(lineDelimiter);
        buf.append(typeContent);
        return buf.toString();
    }

    protected String accessModifiers = "public"; // 初期値 public //$NON-NLS-1$

    protected void createField(IType type, ImportsManager imports, IProgressMonitor monitor) throws JavaModelException {
        IEntityMappingFactory mapping = DefaultEntityMappingFactory.getFactory(entity.getDbConfig());
        StringBuffer buf = new StringBuffer();
        TreeLeaf[] leafs = entity.getChildrens();
        
        StringBuilder toStr = new StringBuilder();
        toStr.append("\t@Override").append("\r\n");
        toStr.append("\tpublic String toString() {").append("\r\n");
        toStr.append("\treturn \""+getTypeName()+" [");
        
        // toString.append(seqContractid=\" + seqContractid + \",  jnrstNo=\" + jnrstNo + \"]\";").append("\r\n");
        //toString.append("\t}").append("\r\n");

        
        for (int i = 0; i < leafs.length; i++) {
            Column col = (Column) leafs[i];

            String propertyName = PropertyNameUtil.getProperty(col, true);
            // if (!superClassFields.contains(propertyName)) {
            buf.append("\t/**").append(lineDelimiter); //$NON-NLS-1$
            buf.append("\t * " + CodeCreatorUtil.getLogicalColumnLabel(col)).append(lineDelimiter); //$NON-NLS-1$
            buf.append("\t */").append(lineDelimiter); //$NON-NLS-1$
            if ("version".equalsIgnoreCase(col.getName())) { //$NON-NLS-1$
                buf.append("\t@").append(imports.addImport("javax.persistence.Version")).append(lineDelimiter); //$NON-NLS-1$ //$NON-NLS-2$
                buf.append("\tpublic Long version = 0L;").append(lineDelimiter); //$NON-NLS-1$
            } else {
                if (col.hasPrimaryKey()) {
                    // buf.append("\t@").append(imports.addImport("javax.persistence.Id")).append(lineDelimiter);
                    // // $NON-NlineDelimiter-1$ //$NON-NlineDelimiter-2$
                    buf.append("\t@").append("Id").append(lineDelimiter); // $NON-NlineDelimiter-1$
                                                                          // //$NON-NlineDelimiter-2$
                }
                // buf.append("\t@").append(imports.addImport("javax.persistence.Column")).append("(name = \""
                // + col.getName() + "\")").append(lineDelimiter); //
                // $NON-NlineDelimiter-1$
                buf.append("\t@").append("Column").append("(name = \"" + col.getName() + "\")").append(lineDelimiter); // $NON-NlineDelimiter-1$

                if (col.isNotNull()) {
                    buf.append("\t@").append("NotNull").append(lineDelimiter); // $NON-NlineDelimiter-1$
                                                                               // //$NON-NlineDelimiter-2$
                }
/*
                switch (col.getColumn().getDataType()) {
                case Types.CHAR:
                case Types.VARCHAR:
                case Types.SMALLINT:
                case Types.INTEGER:
                case Types.REAL:
                case Types.FLOAT:
                case Types.DOUBLE:
                case Types.NUMERIC:
                case Types.DECIMAL:
                case Types.BIGINT:
                    int size = col.getColumn().getColumnSize();
                    int digit = col.getColumn().getDecimalDigits();
                    if (digit == 0) {
                        buf.append("\t@").append("MaxByte(").append(size).append(")").append(lineDelimiter); // $NON-NlineDelimiter-1$
                                                                                                             // //$NON-NlineDelimiter-2$
                    }
                    break;
                default:
                    break;
                }
*/               
                // //$NON-NlineDelimiter-2$
                // //$NON-NlineDelimiter-3$
                // //$NON-NlineDelimiter-4$
                /*
                 * if (mapping.isLargeObject(col.getDataType())) {
                 * buf.append("\t@"
                 * ).append(imports.addImport("javax.persistence.Lob"
                 * )).append(lineDelimiter); // $NON-NlineDelimiter-1$
                 * //$NON-NlineDelimiter-2$ }
                 */

                /*
                 * String temporalType =
                 * mapping.getTemporalType(col.getDataType()); if (temporalType
                 * != null) {
                 * imports.addImport("javax.persistence.TemporalType"); //
                 * $NON-NlineDelimiter-1$
                 * buf.append("\t@").append(imports.addImport
                 * ("javax.persistence.Temporal")).append("(" + temporalType +
                 * ")").append(lineDelimiter);; // $NON-NlineDelimiter-1$ //
                 * //$NON-NlineDelimiter-2$ // //$NON-NlineDelimiter-3$ //
                 * //$NON-NlineDelimiter-4$ }
                 */

                String javaType = getJavaType(col);
                if (javaType.startsWith("java.math.") || javaType.startsWith("java.sql.")) { // $NON-NlineDelimiter-1$
                                                                                             // //$NON-NlineDelimiter-2$
                    javaType = imports.addImport(javaType);
                }
                buf.append("\t").append(propertyString(accessModifiers, javaType, propertyName)); // $NON-NlineDelimiter-1$
                buf.append(lineDelimiter);

                    
                if(i == 0){
                    toStr.append(propertyName).append("=\" + ").append(propertyName);
                }else{
                    toStr.append(" + \", ").append(propertyName).append("=\" + ").append(propertyName);
                }
                
                if(i == leafs.length - 1){
                    toStr.append(" + \"]\";");
                }
                toStr.append(lineDelimiter);
            }
            buf.append(lineDelimiter);
            
        }
        toStr.append("\t}").append("\r\n");
        
        buf.append(lineDelimiter).append(toStr.toString());
        
        type.createField(buf.toString(), null, false, null);
    }

}
