/*********************************************************************
*  All Rights reserved,Copyright (c) K-Opticom						 *
**********************************************************************
*＜プログラム内容＞
*	システム名			：eo顧客基幹システム
*	モジュール名		：JKKTjgsAreaIfAddRsltRcvFile
*	ソースファイル名	：JKKTjgsAreaIfAddRsltRcvFile.java
*	作成者				：富士通　
*	作成日				：2013年01月08日
*＜機能概要＞
*　HTTPファイル受信用アクセスクラス
*＜修正履歴＞
*	バージョン	修正日		修正者		修正内容
*	v5.00.00	2013/01/08   富士通		新規作成
*********************************************************************/
package eo.business.common;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import eo.common.constant.JPCBatchMessageConstant;
import eo.framework.application.JBSbatBusinessException;



/**
 * 他事業者向けエリア情報登録結果ファイル取得<p>
 * 他事業者向けエリア情報登録結果ファイルを取り込む。
 * サイトよりファイル名のリストを取得し、ファイル名の一番大きなもの
 * （日付部分の比較が文字列辞書的に正しく判定されること前提）を取得する。
 * <br>
 * @author 富士通
 */

public class JKKTjgsAreaIfAddRsltRcvFile extends JKKHttpCommunicator {
	/** PROXYホストを取得するキー */
	private static final String T_KEY_PROXY_HOST = "KK_TAIAR_DL_PROXY_HOST";

	/** PROXYポートを取得するキー */
	private static final String T_KEY_PROXY_PORT = "KK_TAIAR_DL_PROXY_PORT";	

	/** リストを受信URLを取得するキー */
	private static final String T_KEY_URL_STR = "KK_TAIAR_DL_URL";
	
	/** 認証ユーザを取得するキー */
	private static final String T_KEY_USER_STR = "KK_TAIAR_DL_USERID";
	
	/** 認証パスワードを取得するキー */
	private static final String T_KEY_PASS_STR = "KK_TAIAR_DL_PASSWD";
	
	/** タイムアウトを取得するキー */
	private static final String T_KEY_TIMEOUT_STR = "KK_TAIAR_DL_TIMEOUT";
	
	/** リトライ数を取得するキー */
	private static final String T_KEY_RETRY_STR = "KK_TAIAR_DL_RETRYCOUNT";
	
	/** リトライ後の待機時間を取得するキー */
	private static final String T_KEY_INTERVAL_STR = "KK_TAIAR_DL_RETRYINTERVAL";
	
	/** ファイル名を取得するための正規表現 */
	private static final String T_FILE_NAME = "ar902043\\.[0-9]{12}";
	
	/** リスト取得モード */
	private static final int LIST_RCV = 0;
	
	/** ファイル取得モード */
	private static final int FILE_RCV = 1;
	
	/** 受信コンテンツの処理モード */
	private int mode = LIST_RCV;
	
	/** 最新のファイル名 */
	private String lastFileName = null;
	
	/** ファイル名をチェックする正規表現 */
	private Pattern pattern = Pattern.compile(T_FILE_NAME);

	private static final String MSG_SETSUZOKU_SAKI = "接続先";
	
	private static final String MSG_SHUTSURYOKU_DIR = "出力先ディレクトリ";
	
	/** 書き込み用 */
	private BufferedWriter writer = null;
	
	/**
	 * デフォルトコンストラクタ
	 */
	public JKKTjgsAreaIfAddRsltRcvFile()
	{
	}
	
	/**
	 * ファイル受信
	 * @param receiveDir ファイル受信ディレクトリ
	 * @throws Exception 例外を返す
	 */
	public void receiveFile(String receiveDir) throws Exception
	{
		// 取得ファイル名を初期化
		lastFileName = null;
		
		// 出力先ディレクトリを取得
		String outFileDir = receiveDir;
		if (outFileDir == null || outFileDir.length() == 0)
		{
			throw new JBSbatBusinessException(JPCBatchMessageConstant.EKKB0890CW, new String[] {MSG_SHUTSURYOKU_DIR});
		}
		
		// PROXYを取得する
		String proxyHost = getApplicationConst(T_KEY_PROXY_HOST, false);
		String proxyPort = getApplicationConst(T_KEY_PROXY_PORT, false);
		
		setProxy(proxyHost, proxyPort);
		
		// 接続先を指定する（必須）
		String urlStr = getApplicationConst(T_KEY_URL_STR, false);
		
		if (urlStr == null || urlStr.length() == 0)
		{
			throw new JBSbatBusinessException(JPCBatchMessageConstant.EKKB0890CW, new String[] {MSG_SETSUZOKU_SAKI});
		}

		// URLに変換
		URL url = new URL(urlStr);
		
		// SSLの場合は証明書関係の初期化を行う
		if (url.getProtocol().equalsIgnoreCase(JKKHttpCommunicator.S_HTTPS))
		{
			JKKHttpCommunicator.initializeSSL();
		}
		
		// 認証情報の取得
		String user   = getApplicationConst(T_KEY_USER_STR, false);
		String passwd = getApplicationConst(T_KEY_PASS_STR, true);	// パスワードは暗号化

		if (user != null && user.length() > 0)
		{
			initializeAuthentication(user, passwd);
		}
		
		// その他の属性を設定
		setTimeout(Integer.parseInt(getApplicationConst(T_KEY_TIMEOUT_STR, false)));
		setRetryCount(Integer.parseInt(getApplicationConst(T_KEY_RETRY_STR, false)));
		setRetryInterval(Integer.parseInt(getApplicationConst(T_KEY_INTERVAL_STR, false)));
		
		// モードをリスト取得に設定する
		mode = LIST_RCV;
		
		// 接続URLの設定
		setTargetURL(url);
					
		// 実行する。
		if (execute()) 
		{
			// ファイルが取得できなかった場合は正常終了
			if (lastFileName == null)
			{
				return;
			}
			// -------------------------------------------------------------
			File outFile = new File(outFileDir, lastFileName);
			
			// ファイル受信モードに指定
			mode = FILE_RCV; 
			// URLの作成
			url = new URL(url,  lastFileName);
			// 新しいURLを指定
			setTargetURL(url);
			try {
				writer = new BufferedWriter(new FileWriter(outFile));

				// 実行する。
				if (execute()) 
				{
				}
				else 
				{
					throw new JBSbatBusinessException(JPCBatchMessageConstant.EKKB0910CW);
				}
			} 
			finally 
			{
				if (writer != null)
				{
					writer.close();
					writer = null;
				}
			}
		}
		else 
		{
			throw new JBSbatBusinessException(JPCBatchMessageConstant.EKKB0900CW);
		}
	}

	/**
	 * 受信データ処理
	 */
	@Override
	protected void receiveContentAtLine(String val) throws IOException 
	{
		if (mode == LIST_RCV)
		{
			// 指定ファイル名を探す
			Matcher m = pattern.matcher(val);
			while (m.find())
			{
				int start = m.start();
				int end   = m.end();
				String work = val.substring(start, end);
				if (lastFileName == null || lastFileName.compareTo(work) < 0)
				{
					lastFileName = work;
				}
				
			}
			
		}
		else 
		{
			// 行データを書き込む
			writer.write(val + "\n");
		}
	}
	
	/**
	 * 受信ファイル存在チェック
	 * <br>
	 * @return 存在する場合はtrue
	 */
	public boolean existReceiveFile() 
	{
		return lastFileName != null;
	}
	
	/**
	 * 受信ファイル名取得
	 * <br>
	 * @return 受信ファイルのファイル名を返す
	 */
	public String getFileName() 
	{
		return lastFileName;
	}
}
