/*
 * step2.java
 *
 * DATE : 2005/11/24 15:46
 *
 * 機種調整値をウェブサーバから取得し
 * スクラッチパッドに保存するテスト
 *
 */
import com.nttdocomo.ui.*;
import com.nttdocomo.io.*;
import java.io.*;
import javax.microedition.io.*;
/**
 * step2
 *
 * @author NAME
 */
public class step2 extends IApplication {

	public void start() {
		/*
		 * The program of IApplication is written here.
		 */
		Display.setCurrent(new MainCanvas());
	}
}

class MainCanvas extends Canvas {

	Image		imgMain;				//メインイメージ：最終形態（キャンバス）
	Image		imgLoadResouce;			//リソースからの読み込みイメージ：作業域
	Image		imgLoadScratchPad;		//スクラッチパッドからの読み込みイメージ：作業域
	Graphics	graMain;				//グラフィックオブジェクト
	String		strGetData;				//サーバから取得した文字列

	int intWidth;						//キャンバスの幅
	int intHeight;						//キャンバスの高さ

	int intAdjustHeight;				//エミュレーターの座標0と実機の座標0との差

	ScratchPadManager mySPManager;		//スクラッチパッド操作クラス

	MainCanvas() 
	{
		//キャンバスのサイズをセット
		intWidth = 240;
		intHeight = 240;

		//エミュレーターより実機は上に2pixcelほど不可視領域がある。
		//でもなぜか画像は調整の必要がない。
		intAdjustHeight = 2;

		//画像が取得できないときヌルポになるので初期化
		imgMain = Image.createImage(intWidth, intHeight);
		imgLoadResouce = Image.createImage(intWidth, intHeight);
		imgLoadScratchPad = Image.createImage(intWidth, intHeight);
		graMain = imgMain.getGraphics();

		//文字も取得できないとヌルポになるので初期化
		strGetData = "";

		//リソースからの読み込み
		try
		{
			MediaImage mediaImg = MediaManager.getImage("resource:///koneko01.gif");
			mediaImg.use();
			imgLoadResouce = mediaImg.getImage();
		}
		catch( ConnectionException e)
		{}
		catch(IOException e)
		{}

		//ウェブサーバからの読み込み、スクラッチパッドへ
		subGetServerData();

		//スクラッチパッドから読み込み
		try
		{
			MediaImage mediaImg = MediaManager.getImage("scratchpad:///0;pos=11");
			mediaImg.use();
			imgLoadScratchPad = mediaImg.getImage();
		}
		catch( ConnectionException e)
		{}
		catch(IOException e)
		{}

		mySPManager = new ScratchPadManager();

		graMain.lock();
		//キャンバスをクリア
		graMain.clearRect(0, 0, intWidth, intHeight);

		//文字を描画　　指定する座標はフォントの左下、デフォルトは
		//　　　　　　　上限マージン１ずつで合計高さ12pixcel
		graMain.drawString("リソースイメージ", 0, 10 + mySPManager.intFontAdjustTop);
		graMain.drawImage(imgLoadResouce, 0, 12);

		//リソースイメージが69pixcelなので69+12+10=91pixcelに文字を
		graMain.drawString("スクラッチパッドイメージ", 0, 91 + mySPManager.intFontAdjustTop);
		graMain.drawImage(imgLoadScratchPad, 0, 93);

		//ウェブのイメージが50pixcelなので91+50+10=153pixcel
		graMain.drawString("WEBから取得したデータ:" + strGetData, 0, 153 + mySPManager.intFontAdjustTop);
		graMain.drawString("ScratchPadに書き込むデータ:" + mySPManager.strGetScratchPadData, 0, 165 + mySPManager.intFontAdjustTop);

		graMain.drawString("intFontAdjustTop:" + Integer.toString(mySPManager.intFontAdjustTop), 0, 177 + mySPManager.intFontAdjustTop);
		graMain.drawString("intFontAdjustLeft:" + Integer.toString(mySPManager.intFontAdjustLeft), 0, 189 + mySPManager.intFontAdjustTop);

		graMain.unlock(true);

		// ソフトキーラベル「back」を作成する。
		setSoftLabel(Frame.SOFT_KEY_1, "Back");

	}

	/**
	* キャンバス領域に描画する。
	*/
	public void paint(Graphics g) 
	{
		g.drawImage(imgMain, 0, 0);
	}

	//サーバから文字と画像を取得する
	synchronized void subGetServerData()
	{
		HttpConnection	httpConn;		//HTTP接続オブジェクト
		InputStream		objInStream;	//入力オブジェクト
		OutputStream	objOutStream;	//出力オブジェクト

		int				intChar;		//取得したデータ
		StringBuffer	strbGetBuffer;	//取得した文字バッファを格納

		strbGetBuffer = new StringBuffer();
		strGetData = "";

		byte[]			bytData;		//読み込みデータ
		int				intLength;		//データの長さ

		try
		{
			// HTTP 接続（HttpConnection）オブジェクトを取得する。
			//httpConn = (HttpConnection)Connector.open("http://machtype.com/~flesh_gogo/cgi-bin/remote_addr.cgi",Connector.READ_WRITE,true);
			httpConn = (HttpConnection)Connector.open("http://machtype.com/~flesh_gogo/cgi-bin/fontadjustpoint.cgi",Connector.READ_WRITE,true);

			// リクエストメソッドを設定する。
			httpConn.setRequestMethod(HttpConnection.GET);

			// リモート資源に接続する。
			httpConn.connect();

			//データをInputStreamに
			objInStream = httpConn.openInputStream();

			//データを文字列にするために、バッファに入れる
			while ((intChar = objInStream.read()) != -1)
			{
				strbGetBuffer.append((char)intChar);
			}

			//文字列に変換
			strGetData = (String)strbGetBuffer.toString();

			// 入力ストリームをクローズする。
			objInStream.close();
			// HTTP 接続をクローズする。
			httpConn.close();

			httpConn = (HttpConnection)(Connector.open("http://machtype.com/~flesh_gogo/mobile-appli/koneko02.gif",Connector.READ));
			httpConn.setRequestMethod(HttpConnection.GET);
			httpConn.connect();
			objInStream=httpConn.openInputStream();

			//スクラッチパットに接続し、出力するオブジェクトを取得
			objOutStream=Connector.openOutputStream("scratchpad:///0;pos=11");
			bytData=new byte[128];
			//データが終わるまでスクラッチパッドに書き込む
			while ((intLength=objInStream.read(bytData)) != -1 )
			{
				objOutStream.write(bytData,0,intLength);
			}

			objInStream.close();
			objOutStream.close();
			httpConn.close();

		}
		catch (ConnectionNotFoundException e)
		{}
		catch(ConnectionException e)
		{}
		catch(IOException e)
		{}
	}
}

class ScratchPadManager
{
	int				intFontAdjustTop;	//フォントの上（座標y=0）からの差
	int				intFontAdjustLeft;	//フォントの左（座標x=0）からの差
	int				intFontAdjustHeight;//フォントの高さの差
	int				intFontAdjustWidth; //フォントの幅の差

	String			strGetScratchPadData;	//サーバから取得した文字列

	ScratchPadManager()
	{
		byte[]			bytData;			//読み込みデータ
		StringBuffer	strbGetBuffer;	//取得した文字バッファを格納

		try
		{
			InputStream	objInStream;	//入力オブジェクト
			//スクラッチパットに接続し、入力するオブジェクトを取得
			objInStream = Connector.openInputStream("scratchpad:///0;pos=0,length=5");

			bytData=new byte[5];
			objInStream.read(bytData);
			objInStream.close();

			strbGetBuffer = new StringBuffer();
			strbGetBuffer.append(bytData[1]);
			System.out.println("subFontAdjustPointSet:bytData[1]=" + strbGetBuffer.toString());

			if(bytData[0] == 0 || bytData[0] == 1 || bytData[0] == 9)
			{//まだ初期設定を取り込めていないので、取り込み開始

				subFontAdjustPointSet();
			}
			else
			{
				//フォントの上（座標y=0）からの差
				//strbGetBuffer = new StringBuffer();
				//strbGetBuffer.append((char)bytData[2]);
				//strbGetBuffer.append((char)bytData[3]);
				//intFontAdjustTop = Integer.parseInt(strbGetBuffer.toString(), 16);
				intFontAdjustTop = (int)bytData[1];
				//System.out.println("intFontAdjustTop=" + intFontAdjustTop);
				//フォントの左（座標x=0）からの差
				//strbGetBuffer = new StringBuffer();
				//strbGetBuffer.append((char)bytData[4]);
				//strbGetBuffer.append((char)bytData[5]);
				//intFontAdjustLeft = Integer.parseInt(strbGetBuffer.toString(), 16);
				intFontAdjustTop = (int)bytData[2];
				//System.out.println("intFontAdjustLeft=" + intFontAdjustLeft);
				//フォントの高さの差
				//strbGetBuffer = new StringBuffer();
				//strbGetBuffer.append((char)bytData[6]);
				//strbGetBuffer.append((char)bytData[7]);
				//intFontAdjustHeight = Integer.parseInt(strbGetBuffer.toString(), 16);
				intFontAdjustTop = (int)bytData[3];
				//System.out.println("intFontAdjustHeight=" + intFontAdjustHeight);
				//フォントの幅の差
				//strbGetBuffer = new StringBuffer();
				//strbGetBuffer.append((char)bytData[8]);
				//strbGetBuffer.append((char)bytData[9]);
				//intFontAdjustWidth = Integer.parseInt(strbGetBuffer.toString(), 16);
				intFontAdjustTop = (int)bytData[4];
				//System.out.println("intFontAdjustWidth=" + intFontAdjustWidth);
			}

		}
		catch (ConnectionNotFoundException e)
		{
			System.out.println("ScratchPadManager():ConnectionNotFoundException");
		}
		catch(ConnectionException e)
		{
			System.out.println("ScratchPadManager():ConnectionException");
		}
		catch(IOException e)
		{
			System.out.println("ScratchPadManager():IOException");
		}
	}

	void subFontAdjustPointSet()
	{//フォント調整値を取得
		HttpConnection	httpConn;		//HTTP接続オブジェクト
		InputStream		objInStream;	//入力オブジェクト
		OutputStream	objOutStream;	//出力オブジェクト

		int				intGetData;
		Integer			objInt;

		int				intLoopCount;
		int				intLength;		//データの長さ

		byte[]			bytGetData;			//読み込みデータ
		byte[]			bytWriteData;		//読み込みデータ
		StringBuffer	strbGetBuffer;	//取得した文字バッファを格納

		try
		{
			// HTTP 接続（HttpConnection）オブジェクトを取得する。
			httpConn = (HttpConnection)Connector.open("http://machtype.com/~flesh_gogo/cgi-bin/fontadjustpoint.cgi",Connector.READ_WRITE,true);

			// リクエストメソッドを設定する。
			httpConn.setRequestMethod(HttpConnection.GET);

			// リモート資源に接続する。
			httpConn.connect();

			//データをInputStreamに
			objInStream = httpConn.openInputStream();

			httpConn.close();

			intGetData = 0;
			bytGetData = new byte[10];
			bytWriteData = new byte[5];
			objInStream.read(bytGetData);
			objInStream.close();

			strGetScratchPadData = "01";

			//フォントの上（座標y=0）からの差
			strbGetBuffer = new StringBuffer();
			strbGetBuffer.append((char)bytGetData[2]);
			strbGetBuffer.append((char)bytGetData[3]);
			intFontAdjustTop = Integer.parseInt(strbGetBuffer.toString(), 16);
			strGetScratchPadData = strGetScratchPadData + strbGetBuffer.toString();
			bytWriteData[1] = Byte.parseByte(strbGetBuffer.toString());
			System.out.println("intFontAdjustTop=" + intFontAdjustTop);
			//フォントの左（座標x=0）からの差
			strbGetBuffer = new StringBuffer();
			strbGetBuffer.append((char)bytGetData[4]);
			strbGetBuffer.append((char)bytGetData[5]);
			intFontAdjustLeft = Integer.parseInt(strbGetBuffer.toString(), 16);
			strGetScratchPadData = strGetScratchPadData + strbGetBuffer.toString();
			bytWriteData[2] = Byte.parseByte(strbGetBuffer.toString());
			//System.out.println("intFontAdjustLeft=" + intFontAdjustLeft);
			//フォントの高さの差
			strbGetBuffer = new StringBuffer();
			strbGetBuffer.append((char)bytGetData[6]);
			strbGetBuffer.append((char)bytGetData[7]);
			intFontAdjustHeight = Integer.parseInt(strbGetBuffer.toString(), 16);
			strGetScratchPadData = strGetScratchPadData + strbGetBuffer.toString();
			bytWriteData[3] = Byte.parseByte(strbGetBuffer.toString());
			//System.out.println("intFontAdjustHeight=" + intFontAdjustHeight);
			//フォントの幅の差
			strbGetBuffer = new StringBuffer();
			strbGetBuffer.append((char)bytGetData[8]);
			strbGetBuffer.append((char)bytGetData[9]);
			intFontAdjustWidth = Integer.parseInt(strbGetBuffer.toString(), 16);
			strGetScratchPadData = strGetScratchPadData + strbGetBuffer.toString();
			bytWriteData[4] = Byte.parseByte(strbGetBuffer.toString());
			//System.out.println("intFontAdjustWidth=" + intFontAdjustWidth);

			//初期設定完了フラグ
			bytWriteData[0] = 01;

			//スクラッチパットに接続し、出力するオブジェクトを取得
			objOutStream=Connector.openOutputStream("scratchpad:///0;pos=0,length=5");

			objOutStream.write(bytWriteData,0,5);

			objOutStream.close();


		}
		catch (ConnectionNotFoundException e)
		{
			System.out.println("subFontAdjustPointSet():ConnectionNotFoundException");
		}
		catch(ConnectionException e)
		{
			System.out.println("subFontAdjustPointSet():ConnectionException");
		}
		catch(IOException e)
		{
			System.out.println("subFontAdjustPointSet():IOException");
		}

	}
}
