/*
 * 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 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_INDEX は、TableUpda インターフェースを継承した、DBTableModel 処理用の
 * 実装クラスです。<br />
 *
 * ここでは、テーブル一覧の検索結果より、GF07 のインデックスカラム定義テーブルから
 * 必要な情報を取得し、インデックス作成スクリプトを作成します。
 * 出力ファイルは、テーブル名＋"I.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_INDEX 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","TABLE_LABEL","INDEX_NAME","NAME_JA","INDTYPE",
							"TABLESPACE_NAME","INITIAL_EXTENT","NEXT_EXTENT" };

	private static final int SYSTEM_ID			= 0;
	private static final int TBLSYU				= 1;
	private static final int TABLE_NAME			= 2;
	private static final int TABLE_LABEL		= 3;	// GF02 の NAME_JA より JOIN
	private static final int INDEX_NAME			= 4;
	private static final int INDTYPE			= 6;
	private static final int TABLESPACE_NAME	= 7;
	private static final int INITIAL_EXTENT		= 8;
	private static final int NEXT_EXTENT		= 9;

	private static final String GF07_SEL = "select CLM"
											+ " from GF07"
											+ " where SYSTEM_ID=? and TBLSYU=? and TABLE_NAME=? and INDEX_NAME=?"
											+ " and   FGJ='1'"
											+ " order by SEQNO" ;

//	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) 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 );
		}

		String[] data  = null;
		String bkTableName = null;
		PrintWriter writer = null;
		for( int row=0; row<rowCnt; row++ ) {
			String tableName = null;
	//		String tableLbl  = null;
			String indexName = null;
			try {
				data  = table.getValues( row );
				String systemId  = data[clmNo[SYSTEM_ID]];
				String tblsyu    = data[clmNo[TBLSYU]];
				tableName = data[clmNo[TABLE_NAME]];
	//			tableLbl  = data[clmNo[TABLE_LABEL]];
				indexName = data[clmNo[INDEX_NAME]];

				// テーブルがキーブレイクすると、セーブファイルを切り替える。
				if( ! tableName.equals( bkTableName ) ) {
					if( writer != null ) {
						if( isXml ) { writer.println( XML_END_TAG ); }
						writer.close();
					}
					bkTableName = tableName;
					writer = FileUtil.getPrintWriter( new File( dir,tableName + "I." + ( isXml ? "xml" : "sql" ) ),ENCODE );
					if( isXml ) { writer.println( XML_START_TAG ); }
					writer.println( makeHeadLine( clmNo,data ) );
				}

				String[] vals = new String[] { systemId,tblsyu,tableName,indexName };
				String[][] gf07 = DBUtil.dbExecute( GF07_SEL,vals,appInfo );
				if( gf07.length == 0 ) {
					System.out.println( "TABLE=" + tableName + " , INDEX=" + indexName + " is Not Found!" );
					continue;
				}
				// テーブルに対するカラム列
				StringBuilder buf = new StringBuilder() ;
				for( int j=0; j<gf07.length; j++ ) {
					buf.append( gf07[j][0] ).append( "," );
				}
				buf.deleteCharAt( buf.length()-1 );

				String clms = buf.toString();

				writer.println( makeLineList( clmNo,data,clms ) );
				writer.println( makeEndLine( clmNo,data ) );
			}
			catch( RuntimeException ex ) {
				ErrorMessage errMessage = makeErrorMessage( "TableFilter_INDEX Error",ErrorMessage.NG );
				errMessage.addMessage( row+1,ErrorMessage.NG,"INDEX",ex.getMessage() );
				errMessage.addMessage( row+1,ErrorMessage.NG,"INDEX",StringUtil.array2csv( data ) );
				errMessage.addMessage( row+1,ErrorMessage.NG,"INDEX","TABLE=[" + tableName + "],INDEX=[" + indexName + "]" );
			}
		}
		if( isXml ) { writer.println( XML_END_TAG ); }
		if( writer != null ) { writer.close(); }

		return table;
	}

	protected String makeHeadLine( final int[] clmNo,final String[] data ) {
//		String LINE1 = data[clmNo[TABLE_NAME]] ;
		String tableName = data[clmNo[TABLE_NAME]];
		String LINE1 = tableName + " ( " + data[clmNo[TABLE_LABEL]] + " )" ;
		String LINE2 = "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,	" */" },
			{ "/**",	CMNT ,	"**/" },
		};

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

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

		return buf.toString();
	}

	protected String makeLineList( final int[] clmNo,final String[] data,final String clms ) {
		String tableName = data[clmNo[TABLE_NAME]];
		String indexName = data[clmNo[INDEX_NAME]];
		String idxtype   = data[clmNo[INDTYPE]];

		StringBuilder buf = new StringBuilder();

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

		if( "1".equals( idxtype ) ) {	// ユニークキー
			buf.append( "ALTER TABLE " ).append( tableName ).append( " ADD CONSTRAINT " );
			buf.append( indexName ).append( " UNIQUE( " ).append( clms );
			buf.append( " )" );
		}
		else {
			buf.append( "CREATE INDEX " ).append( indexName ).append( " ON " );
			buf.append( tableName ).append( "( " ).append( clms );
			buf.append( " )" );
		}

		return buf.toString();
	}

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

		String idxtype   = data[clmNo[INDTYPE]];
		if( "1".equals( idxtype ) ) {	// ユニークキー
			buf.append( "USING INDEX " );
		}

		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();
	}
}
