/*
 * Copyright (c) 2009 The openGion Project.
 *
 * 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 org.opengion.plugin.table;

import java.io.File;
import java.io.PrintWriter;
import java.util.Locale;

import org.opengion.fukurou.db.DBUtil;
import org.opengion.fukurou.util.FileUtil;
import org.opengion.fukurou.util.FixLengthData;
import org.opengion.fukurou.util.StringUtil;
import org.opengion.hayabusa.common.ErrorMessage;
import org.opengion.hayabusa.common.HybsSystem;
import org.opengion.hayabusa.common.HybsSystemException;
import org.opengion.hayabusa.db.DBTableModel;

/**
 * <p>TableFilter_TABLE は、TableFilter インターフェースを継承した、DBTableModel 処理用の
 * 実装クラスです。<br />
 *
 * ここでは、テーブル一覧の検索結果より、GF05 のテーブルカラム定義テーブルから
 * 必要な情報を取得し、テーブル作成スクリプトを作成します。
 * 出力ファイルは、テーブル名＋"S.sql" という命名規則で作成します。
 * 検索では、(SYSTEM_ID,TBLSYU,TABLE_NAME,NAME_JA,TABLESPACE_NAME,INITIAL_EXTENT,NEXT_EXTENT,COMMENTS)
 * の項目を取得する必要があります。
 *
 * @version  0.9.0  2000/10/17
 * @author   Kazuhiko Hasegawa
 * @since    JDK1.1,
 */
public class TableFilter_TABLE extends AbstractTableFilter {
	//* このプログラムのVERSION文字列を設定します。	{@value} */
	private static final String VERSION = "4.0.0 (2005/08/31)" ;

	private static final String[] DBKEY = {"SYSTEM_ID","TBLSYU","TABLE_NAME","NAME_JA",
							"TABLESPACE_NAME","INITIAL_EXTENT","NEXT_EXTENT","COMMENTS" };

	private static final int SYSTEM_ID			= 0;
	private static final int TBLSYU				= 1;
	private static final int TABLE_NAME			= 2;
	private static final int NAME_JA			= 3;
	private static final int TABLESPACE_NAME	= 4;
	private static final int INITIAL_EXTENT		= 5;
	private static final int NEXT_EXTENT		= 6;
	private static final int COMMENTS			= 7;

	private static final String GF05_SEL = "select CLM,SEQNO,NAME_JA,CLS_NAME,USE_LENGTH,DATA_DEFAULT,NOT_NULL,'' AS OPTS"
											+ " from GF05"
											+ " where SYSTEM_ID=? and TBLSYU=? and TABLE_NAME=?"
											+ " and   FGJ='1'"
											+ " order by SEQNO" ;

	protected static final int GF05_CLM			= 0;
	protected static final int GF05_SEQNO		= 1;
	protected static final int GF05_NAME_JA		= 2;
	protected static final int GF05_CLS_NAME	= 3;
	protected static final int GF05_USE_LENGTH	= 4;
	protected static final int GF05_DATA_DEFAULT= 5;
	protected static final int GF05_NOT_NULL	= 6;
	protected static final int GF05_OPTIONS		= 7;

//	private static final String ENCODE = "Windows-31J" ;
	private static final String ENCODE = "UTF-8" ; // 4.3.6.6 (2009/05/15)
	private static final String CR     = HybsSystem.CR ;

	private static final String CMNT  = "**********************************************************************" ;

	private static final int X = FixLengthData.X ;
	private static final int K = FixLengthData.K ;

	protected static final String XML_START_TAG	= "<?xml version='1.0' encoding='UTF-8'?>" + CR + "<ROWSET tableName='xxx'>";
	protected static final String XML_END_TAG	= "</ROWSET>";
	protected static final String EXEC_START_TAG= "<EXEC_SQL>";
	protected static final String EXEC_END_TAG	= "</EXEC_SQL>";
	protected boolean		isXml				= false; // 4.3.7.0 (2009/06/01)

	/**
	 * DBTableModel処理を実行します。<br />
	 *
	 * @og.rev 3.8.7.0 (2006/12/15) アクセスログ取得の為,ApplicationInfo オブジェクトを設定
	 * @og.rev 4.0.0.0 (2007/11/28) メソッドの戻り値をチェックします。
	 * @og.rev 4.3.7.0 (2009/06/01) トリガー、SEQUENCE作成機能、XML出力機能追加
	 *
	 * @return DBTableModel
	 */
	public DBTableModel execute() {
		isXml = StringUtil.nval( getValue( "XML" ), false );
		
		int[] clmNo = getTableColumnNo( DBKEY );
		int rowCnt = table.getRowCount();

		File dir = new File( getValue( "DIR" ) );
		if( ! dir.exists() && ! dir.mkdirs() ) {
			String errMsg = "所定のフォルダが作成できませんでした。[" + dir + "]" ;
			// 4.3.4.4 (2009/01/01)
			throw new HybsSystemException( errMsg );
		}

		// カンマ、カラム、クラス(桁数)、初期値、NOT_NULL、独自拡張、行番号、名称、終了
		FixLengthData fixData = new FixLengthData(9);

		int[] addLen = new int[] { 0,1,1,1,1,5,1,0,0 };	// 各データ間のスペース
		int[] type   = new int[] { X,X,X,X,X,X,X,K,X };	// 各データの種別 X:半角 S:ゼロ埋め K:全角混在
		fixData.setAddLength( addLen );
		fixData.setType( type );

		String[] data  = null;
		for( int row=0; row<rowCnt; row++ ) {
			String tableName = null;
			try {
				data  = table.getValues( row );
				String systemId  = data[clmNo[SYSTEM_ID]];
				String tblsyu    = data[clmNo[TBLSYU]];
				tableName = data[clmNo[TABLE_NAME]];

				PrintWriter writer = FileUtil.getPrintWriter( new File( dir,tableName + "S." + ( isXml ? "xml" : "sql" ) ),ENCODE );

				if( isXml ) { writer.println( XML_START_TAG ); }
				writer.println( makeHeadLine( clmNo,data ) );

				String[] vals = new String[] { systemId,tblsyu,tableName };
				String[][] gf05 = DBUtil.dbExecute( GF05_SEL,vals,appInfo );

				String uniqName = null;
				fixData.clear();
				// 値セット：まずは、最大長を求める必要がある。
				for( int i=0; i<gf05.length; i++ ) {
					String[] outData = makeLineList( gf05[i],i==0 );
					fixData.addListData( outData );

					// 4.3.7.0 (2009/06/01)
					if( "UNIQ".equalsIgnoreCase( gf05[i][GF05_CLM] ) || "UNIQSEQ".equalsIgnoreCase( gf05[i][GF05_CLM] ) ) {
						uniqName = gf05[i][GF05_CLM].toUpperCase( Locale.JAPAN );
					}
				}
				// 固定長化：最大長であわせた文字列を出力します。
				for( int i=0; i<gf05.length; i++ ) {
					writer.println( fixData.getFixData( i ) );
				}
				writer.println( makeEndLine( clmNo,data ) );

				// 4.3.7.0 (2009/06/01) UNIQ項目のSEQとトリガーを作成
				if( uniqName != null ) {
					writer.println( makeUniqSeq( clmNo,data ) );
					writer.println( makeUniqTrig( clmNo,data, uniqName ) );
				}

				if( isXml ) { writer.println( XML_END_TAG ); }
				writer.close();
			}
			catch( RuntimeException ex ) {
				ErrorMessage errMessage = makeErrorMessage( "TableFilter_TABLE Error",ErrorMessage.NG );
				errMessage.addMessage( row+1,ErrorMessage.NG,"TABLE",ex.getMessage() );
				errMessage.addMessage( row+1,ErrorMessage.NG,"TABLE",StringUtil.array2csv( data ) );
				errMessage.addMessage( row+1,ErrorMessage.NG,"TABLE","TABLE=[" + tableName + "]" );
			}
		}

		return table;
	}

	protected String makeHeadLine( final int[] clmNo,final String[] data ) {

		String tableName = data[clmNo[TABLE_NAME]];

		String LINE1 = tableName + " ( " + data[clmNo[NAME_JA]] + " )" ;
		String LINE2 = data[clmNo[COMMENTS]] ;
		String LINE3 = "Created : " + HybsSystem.getDate() ;

		FixLengthData fixData = new FixLengthData(3);

		int[] addLen = new int[] { 0,0,0 };	// 各データ間のスペース
		int[] type   = new int[] { X,K,X };	// 各データの種別 X:半角 S:ゼロ埋め K:全角混在
		fixData.setAddLength( addLen );
		fixData.setType( type );

		String[][] outData = new String[][] {
			{ "/**",	CMNT ,	"**/" },
			{ "/* ",	LINE1,	" */" },
			{ "/* ",	LINE2,	" */" },
			{ "/* ",	LINE3,	" */" },
			{ "/**",	CMNT ,	"**/" },
		};

		for( int i=0; i<outData.length; i++ ) {
			fixData.addListData( outData[i] );
		}

		StringBuilder buf = new StringBuilder();
		if( isXml ) { buf.append( EXEC_START_TAG ).append( CR ); }
		for( int i=0; i<outData.length; i++ ) {
			buf.append( fixData.getFixData( i ) ).append( CR );
		}

		buf.append( "CREATE TABLE " ).append( tableName ).append( " (" );

		return buf.toString();
	}

	protected String[] makeLineList( final String[] data,final boolean first ) {
		// カンマ、カラム、クラス(桁数)、初期値、NOT_NULL、独自拡張、行番号、名称、終了
		String[] outData = new String[9];
		String clsName = data[GF05_CLS_NAME];

		outData[0] = ( first ) ? "   " : " , " ;			// カンマ
		outData[1] = data[GF05_CLM] ;						// カラム

		if( clsName.startsWith( "CLOB" ) || clsName.startsWith( "DATE" ) ) {
			data[GF05_USE_LENGTH] = null;
		}
		String useLen = data[GF05_USE_LENGTH];
		if( useLen != null && ! useLen.equals( "0" ) ) {
			outData[2] = clsName + "(" + useLen + ")" ;	// クラス(桁数)
		}
		else {
			outData[2] = clsName ;
		}

		String def = data[GF05_DATA_DEFAULT];
		if( def != null && def.length() > 0 ) {
			String comma = ( clsName.indexOf( "CHAR" ) >= 0 ) ? "'" : "" ;
			outData[3] = "   DEFAULT " + comma + def + comma ;	// 初期値
		}

		String notNull = data[GF05_NOT_NULL];
		if( notNull != null && notNull.equals( "1" ) ) {
			outData[4] = "NOT NULL"	;							// NOT_NULL
		}

		String options = data[GF05_OPTIONS];
		if( options != null ) {
			outData[5] = options	;							// 拡張機能
		}

		String nameJA = data[GF05_NAME_JA] ;					// 名称
		if( nameJA != null ) {
			outData[6] = "/* " + data[GF05_SEQNO] ;				// 行番号
			outData[7] = nameJA ;								// 名称
			outData[8] = " */" ;								// 終了
		}

		return outData ;
	}

	protected String makeEndLine( final int[] clmNo,final String[] data ) {
		StringBuilder buf = new StringBuilder();

		buf.append( ")" ).append( CR );
		buf.append( "TABLESPACE " ).append( data[clmNo[TABLESPACE_NAME]] ).append( CR );
		buf.append( "STORAGE( INITIAL " ).append(  data[clmNo[INITIAL_EXTENT]] );
		buf.append( "K NEXT " ).append(  data[clmNo[NEXT_EXTENT]] );
		buf.append( "K PCTINCREASE 0 )" );
		
		if( isXml )	{ buf.append( CR ).append( EXEC_END_TAG ).append( CR ); }
		else		{ buf.append( ";" ).append( CR ); }

		return buf.toString();
	}

	protected String makeUniqSeq( final int[] clmNo,final String[] data ) {
		StringBuilder buf = new StringBuilder();

		if( isXml ) { buf.append( EXEC_START_TAG ).append( CR ); }

		buf.append( "CREATE SEQUENCE " ).append( data[clmNo[TABLE_NAME]] ).append( "S01 " ).append( CR );
		buf.append( "INCREMENT BY 1 ");
		buf.append( "START WITH 1 " );
		buf.append( "MAXVALUE 999999999 " );
		buf.append( "CYCLE NOCACHE" );

		if( isXml )	{ buf.append( CR ).append( EXEC_END_TAG ).append( CR ); }
		else		{ buf.append( ";" ).append( CR ); }

		return buf.toString();
	}

	protected String makeUniqTrig( final int[] clmNo,final String[] data, final String uniqName ) {
		StringBuilder buf = new StringBuilder();

		if( isXml ) { buf.append( EXEC_START_TAG ).append( CR ); }

		buf.append( "CREATE OR REPLACE TRIGGER " ).append( data[clmNo[TABLE_NAME]] ).append( "T01 " ).append( CR );
		buf.append( "BEFORE INSERT ON ").append( data[clmNo[TABLE_NAME]] ).append( CR );
		buf.append( "FOR EACH ROW " ).append( CR );
		buf.append( "BEGIN " ).append( CR );
		buf.append( "SELECT " ).append( data[clmNo[TABLE_NAME]] ).append( "S01.NEXTVAL INTO :NEW." )
			.append( uniqName ).append( " FROM DUAL; " ).append( CR );
		buf.append( "END; " ).append( CR );
		
		if( isXml )	{ buf.append( EXEC_END_TAG ).append( CR ); }
		else		{ buf.append( "/" ).append( CR ); }

		return buf.toString();
	}
}
