package com.tcl.factory.view;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.WindowManager;
import android.widget.TextView;

import com.tcl.customerapi.R;
import com.tcl.factory.bsp.TCL;
import com.tcl.factory.def.KeyMap;
import com.tcl.factory.thirdparty.ThirdParty;

public class USBUpgradeRC65Dialog extends Dialog {
	private Timer timer = new Timer();
	private int count = 0;
	private TextView hintText = null;
	private static boolean threadRunnig = false;
	private static String TAG = "USBUpgradeDialog";
//	private static String RC950_upgrade_fileName = "/data/dongle_update_nfc_is_ok_or_not";

//	public static int UPGRATE_END_FAIL = 0;
//	public static int UPGRATE_END_SUCCESS = 1;
//	public static int UPGRATE_END_FILE_NOT_FOUND = 2;
//	public static int UPGRATE_END_NO_USB = 3;
//	public static int UPGRATE_START = 4;
//	public static int TIMEOUT = 5;
	// jiangt add for RC71
//	public static int TIMEOUT_MAXNUM = 50;
	public static int TIMEOUT_MAXNUM = 50;
//	public static int NO_DONGLE_PLUG_IN = 6;
//	public static int FAIL_FIND_BIN_IN_UDISK = 7;
//	public static int FAIL_SET_DONGLE_ISP_MODE = 8;
//	public static int SUCCESS_BURN_DONGLE = 9;
//	public static int FAIL_BURN_DONGLE = 10;
//	public static int SUCCESS_INIT_DONGLE = 11;
//	public static int FAIL_INIT_DONGLE = 12;
//	public static int RC71_Dongle_Update_ALL_FAIL = 13;
//	public static int FAIL_SET_DONGLE_NORMAL_MODE = 14;
	
	
	public final static int NO_DONGLE_PLUG_INTO = 0x1;//   δ����dongle
	public final static int CANT_FIND_BIN_IN_UDISK = 0x02;//  δ��U�����ҵ����ļ�
	public final static int CANT_FIND_BIN_IN_POINT = 0x03;//   δ��ϵͳ���ҵ����õ����ļ�
	public final static int SUCCESS_BURN_DONGLE = 0x4;//     ��dongle�ɹ�
	public final static int FAIL_BURN_DONGLE = 0x5;//           ��дʧ��
	public final static int SUCCESS_INIT_DONGLE = 0x6;//       ��ʼ���ɹ�
	public final static int CANT_INIT_DONGLE = 0x7;//           ��ʼ��ʧ��
	
	public final static int UPGRATE_END_NO_USB = 8;
	public final static int UPGRATE_START = 9;
	public final static int TIMEOUT = 10;

	public static final String[] upgradeStatus = { "", 
		"NO_DONGLE_PLUG_INTO",        // 1
		"CANT_FIND_BIN_IN_UDISK",     // 2
		"CANT_FIND_BIN_IN_POINT",     // 3
		"SUCCESS_BURN_DONGLE",        // 4
		"FAIL_BURN_DONGLE",           // 5
		"SUCCESS_INIT_DONGLE",        // 6
		"CANT_INIT_DONGLE",           // 7
		"UPGRATE_END_NO_USB",         // 8
		"Upgradeing!!!Please Wait...",// 9 
		};
	
	// end
	// ProgressDialog progressDialog ;
	// jiangt add for RC71
//	public static final String[] upgradeStatus = { "Fail!", "Success!",
//			"File Not Found!", "Please Plug USB!",
//			"Upgradeing!!!Please Wait...", "Rebooting!!!Please Wait...",
//			"NO_DONGLE_PLUG_IN", "FAIL_FIND_BIN_IN_UDISK",
//			"FAIL_SET_DONGLE_ISP_MODE", "SUCCESS_BURN_DONGLE",
//			"FAIL_BURN_DONGLE", "SUCCESS_INIT_DONGLE", "FAIL_INIT_DONGLE",
//			"Dongle_Update_ALL_FAIL", "FAIL_SET_DONGLE_NORMAL_MODE" };

	// end
//	public enum EnumUpgradeStatus {
//		// status fail
//		E_UPGRADE_FAIL,
//		// status success
//		E_UPGRADE_SUCCESS,
//		// file not found
//		E_UPGRADE_FILE_NOT_FOUND,
//	}

	public USBUpgradeRC65Dialog(Context context) {
		super(context, R.style.CustomDialog);

		// usbman = (UsbManager)
		// context.getApplicationContext().getSystemService(Context.USB_SERVICE);

	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		Log.d(TAG, "----onCreate   test----");
		if (threadRunnig) {
			return;
		} else {
			threadRunnig = true;// thread lock
		}
		WindowManager.LayoutParams lp = getWindow().getAttributes();
		lp.y = 300;
		lp.x = 50;
		setContentView(R.layout.fac_dialoghint);
		hintText = (TextView) findViewById(R.id.hint);
		hintText.setText("oncreate");
		timer.schedule(task, 0, 1000);
		// thread = new USBUpgradeThread(this);
		// show();
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		Log.d(TAG, "----onStart----");
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		Log.d(TAG, "----onStop----");

		handler = null;
	}

	public Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			Log.d("Upgrade_RC71", "received message,message.what =" + msg.what);
			if (msg.what == UPGRATE_START) {
				hintText.setText(upgradeStatus[UPGRATE_START]);

				Log.e("Upgrade_RC71", "UPGRATE_START ");
//			} else if (msg.what == UPGRATE_END_SUCCESS) {
//				hintText.setText(upgradeStatus[UPGRATE_END_SUCCESS]);
//				Log.e("Upgrade_RC71", "UPGRATE_END_SUCCESS ");
//				count = TIMEOUT_MAXNUM - 2;
			} else if (msg.what == UPGRATE_END_NO_USB) {
				Log.e("Upgrade_RC71", "UPGRATE_END_NO_USB ");
				// hintText.setText(upgradeStatus[UPGRATE_END_NO_USB]);
				hintText.setText("Please Plug USB!");
				count = TIMEOUT_MAXNUM - 2;
//			} else if (msg.what == UPGRATE_END_FILE_NOT_FOUND) {
//				hintText.setText(upgradeStatus[UPGRATE_END_FILE_NOT_FOUND]);
//				Log.e("Upgrade_RC71", "UPGRATE_END_FILE_NOT_FOUND ");
//				count = TIMEOUT_MAXNUM - 2;
//			} else if (msg.what == UPGRATE_END_FAIL) {
//				hintText.setText(upgradeStatus[UPGRATE_END_FAIL]);
//				Log.e("Upgrade_RC71", "UPGRATE_END_FAIL ");
//				count = TIMEOUT_MAXNUM - 2;
			}
			// jiangt add for RC71
			else if (msg.what == NO_DONGLE_PLUG_INTO) {
				hintText.setText(upgradeStatus[NO_DONGLE_PLUG_INTO]);
				Log.e("Upgrade_RC71", "NO_DONGLE_PLUG_IN ");
				count = TIMEOUT_MAXNUM - 4;
			} else if (msg.what == CANT_FIND_BIN_IN_UDISK) {
				hintText.setText(upgradeStatus[CANT_FIND_BIN_IN_UDISK]);
				Log.e("Upgrade_RC71", "FAIL_FIND_BIN_IN_UDISK ");
				count = TIMEOUT_MAXNUM - 4;
			} else if (msg.what == CANT_FIND_BIN_IN_POINT) {
				hintText.setText(upgradeStatus[CANT_FIND_BIN_IN_POINT]);
				Log.e("Upgrade_RC71", "CANT_FIND_BIN_IN_POINT ");
				count = TIMEOUT_MAXNUM - 4;
			} else if (msg.what == SUCCESS_BURN_DONGLE) {
				hintText.setText(upgradeStatus[SUCCESS_BURN_DONGLE]);
				Log.e("Upgrade_RC71", "SUCCESS_BURN_DONGLE ");
				count = TIMEOUT_MAXNUM - 4;
			} else if (msg.what == FAIL_BURN_DONGLE) {
				hintText.setText(upgradeStatus[FAIL_BURN_DONGLE]);
				Log.e("Upgrade_RC71", "FAIL_BURN_DONGLE ");
				count = TIMEOUT_MAXNUM - 4;
			} else if (msg.what == SUCCESS_INIT_DONGLE) {
				hintText.setText(upgradeStatus[SUCCESS_INIT_DONGLE]);
				Log.e("Upgrade_RC71", "SUCCESS_INIT_DONGLE ");
				count = TIMEOUT_MAXNUM - 4;
			} else if (msg.what == CANT_INIT_DONGLE) {
				hintText.setText(upgradeStatus[CANT_INIT_DONGLE]);
				Log.e("Upgrade_RC71", "FAIL_INIT_DONGLE ");
				count = TIMEOUT_MAXNUM - 4;
//			} else if (msg.what == RC71_Dongle_Update_ALL_FAIL) {
//				hintText.setText(upgradeStatus[RC71_Dongle_Update_ALL_FAIL]);
//				Log.e("Upgrade_RC71", "RC71_Dongle_Update_ALL_FAIL ");
//				count = TIMEOUT_MAXNUM - 4;
//			} else if (msg.what == FAIL_SET_DONGLE_NORMAL_MODE) {
//				hintText.setText(upgradeStatus[FAIL_SET_DONGLE_NORMAL_MODE]);
//				Log.e("Upgrade_RC71", "FAIL_SET_DONGLE_NORMAL_MODE ");
//				count = TIMEOUT_MAXNUM - 4;
			}
			// end
			else if ((msg.what == TIMEOUT) && (threadRunnig == true)) {
				Log.d("Upgrade_RC71", "count is  " + count);
				if (count >= TIMEOUT_MAXNUM) {
					// ˢ��Dongle�汾��
					MainMenu.updateDetailInfoLayer();
					Log.e("Upgrade_RC71", "before timer.cancel ");
					timer.cancel();
					Log.e("Upgrade_RC71", "before task.cancel ");
					task.cancel();
					count = 0;
					dismiss();
					threadRunnig = false;
					Log.d("Upgrade_RC71",
							" count >=Timout_maxnum,threadRunnig = false;");
				}
			}
			super.handleMessage(msg);
		}
	};

	TimerTask task = new TimerTask() {
		@Override
		public void run() {
			Message message = new Message();
			message.what = TIMEOUT;
			count++;
			Log.d("Upgrade_RC71", "send timeoutmessage,count ++,count ="
					+ count);
			handler.sendMessage(message);
		}
	};

	public boolean dispatchKeyEvent(KeyEvent event) {
		if (event.getAction() == KeyEvent.ACTION_DOWN) {
			switch (event.getKeyCode()) {
			// cancel the dialog
			case KeyMap.KEYCODE_HOME:
			case KeyEvent.KEYCODE_MENU:
				dismiss();
				break;
			}
		}
		return true;
	}

	public void UpgradeDialogConfirm() {
		Log.e("UpgradeDialogConfirm", " == ");
		// /////////////////////////////////////////////////////////////////
		// jiangt add for upgrade RC71 dongle begin 2014-01-14
		// progressDialog = new ProgressDialog(ThirdParty.mContext);
		// progressDialog.setMessage("���С�����");
		//
		if (CheckUsbIsExist() == true) {
			Log.d("Upgrade_RC71", "CheckUsbIsExist() == true");
			UpgradeRC71();
		} else {
			handler.sendEmptyMessage(UPGRATE_END_NO_USB);
		}
		// linxp add for upgrade RC950 dongle end 2013-08-23
	}

	public boolean CheckUsbIsExist() {
		if (TCL.getUSBStatus() == true) {
			Log.d("Upgrade_RC71", "getUSBStatus == true");
			// UpgradeRC71();
			Log.d("Upgrade_RC71", "CheckUsbIsExist return true");
			return true;
		}
		Log.d("Upgrade_RC71", "CheckUsbIsExist return false");
		return false;
	}

	// jiangt add for upgrade RC71 dongle begin 2014-01-14
	public boolean UpgradeRC71() {
		Log.d("Upgrade_RC71", "UpgradeRC71 begin");
		new Thread(new Runnable() {
			@Override
			public void run() {
				if (handler != null) {
					// int upgrate_status;
					Log.d("Upgrade_RC71", "threadRunnig = true;");
					threadRunnig = true;
					handler.sendEmptyMessage(UPGRATE_START);
					Log.d("Upgrade_RC71", "UpgradeRC71Fun ");
					ThirdParty.setRootSeek("su &");
					Log.d("Upgrade_RC71", "su");
					ThirdParty.setRootSeek("busybox killall xfsmd-v &");
					Log.d("Upgrade_RC71", "busybox killall xfsmd-v");
					ThirdParty.setRootSeek("rm /data/dongle_update_flag.ini");
					Log.d("Upgrade_RC71", "rm /data/dongle_update_flag.ini");
					ThirdParty.setRootSeek("mount -o remount rw system");
					Log.d("Upgrade_RC71", "mount -o remount rw system");
					ThirdParty.setRootSeek("/system/xbin/dongle_assist_nfc -u");
					Log.d("Upgrade_RC71", "/system/xbin/dongle_assist_nfc -u");
				}
				try {
					// �ȴ��¼���һ��
					Log.d("Upgrade_RC71", "Thread.sleep begin");
					Thread.sleep(2000);
					Log.d("Upgrade_RC71", "Thread.sleep end");
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				Log.d("Upgrade_RC71", "before UpgradeRC71Fun");
				UpgradeRC71Fun();
				Log.d("Upgrade_RC71",
						"after UpgradeRC71Fun,threadRunnig = false;");
				threadRunnig = false;
			}
		}).start();
		return true;
	}

	public void UpgradeRC71Fun() {
		String fileName = "/data/dongle_update_flag.ini";
		Log.d("Upgrade_RC71", "fileName is" + fileName);
		ThirdParty.setRootSeek("chmod 777 /data/dongle_update_flag.ini");
		try {
			Thread.sleep(3000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Log.d("Upgrade_RC71", "UpgradeRC71Fun 1");
		InputStream in = null;
		File file = new File(fileName);
		short[] buffer = new short[10];
		int tempbyte;
		int i = 0;
		try {
			in = new FileInputStream(file);
			Log.d("Upgrade_RC71", "UpgradeRC71Fun 2");
			while ((tempbyte = in.read()) != -1) {
				System.out.write(tempbyte);
				buffer[i] = (short) tempbyte;
				Log.d("Upgrade_RC71", "tempbyte" + tempbyte);
				// Log.d("Upgrade_RC71",
				// "===="+i+"===="+Integer.toHexString(tempbyte));
				// Log.d("Upgrade_RC71",+i+"===="+Integer.toHexString(tempbyte));
				++i;
			}
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		Log.d("Upgrade_RC71", "before Rc71_show");
		Rc71_show(buffer[0]);
	}

	public void Rc71_show(int temp) {
		Log.d("Upgrade_RC71", "temp" + temp);
		temp =  (temp - 48);
		Log.d("Upgrade_RC71", "temp" + temp);
		switch (temp) {
		case NO_DONGLE_PLUG_INTO:
			handler.sendEmptyMessage(NO_DONGLE_PLUG_INTO);
			Log.d("Upgrade_RC71", "showstr" + temp);
			break;
		case CANT_FIND_BIN_IN_UDISK:
			handler.sendEmptyMessage(CANT_FIND_BIN_IN_UDISK);
			Log.d("Upgrade_RC71", "showstr" + temp);
			break;
		case CANT_FIND_BIN_IN_POINT:
			handler.sendEmptyMessage(CANT_FIND_BIN_IN_POINT);
			Log.d("Upgrade_RC71", "showstr" + temp);
			break;
		case SUCCESS_BURN_DONGLE:
			handler.sendEmptyMessage(SUCCESS_BURN_DONGLE);
			Log.d("Upgrade_RC71", "showstr" + temp);
			break;
		case FAIL_BURN_DONGLE:
			handler.sendEmptyMessage(FAIL_BURN_DONGLE);
			Log.d("Upgrade_RC71", "showstr" + temp);
			break;
		case SUCCESS_INIT_DONGLE:
			handler.sendEmptyMessage(SUCCESS_INIT_DONGLE);
			Log.d("Upgrade_RC71", "showstr" + temp);
			break;
		case CANT_INIT_DONGLE:
			handler.sendEmptyMessage(CANT_INIT_DONGLE);
			Log.d("Upgrade_RC71", "showstr" + temp);
			break;
		case UPGRATE_END_NO_USB:
			handler.sendEmptyMessage(UPGRATE_END_NO_USB);
			Log.d("Upgrade_RC71", "showstr" + temp);
			break;
		case UPGRATE_START:
			handler.sendEmptyMessage(UPGRATE_START);
			Log.d("Upgrade_RC71", "showstr" + temp);
			break;
		}
		try {
			Thread.sleep(5000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Log.d("Upgrade_RC71", "before xfsmd -u -h -p 3 &");
		ThirdParty.setRootSeek("xfsmd -u -h -p 3 &");
		Log.d("Upgrade_RC71", "after xfsmd -u -h -p 3 &");
	}

//	public String readFile(String filename) {
//		String res = "error";
//		String fileName = filename;
//		try {
//			InputStream is = new FileInputStream(fileName);
//			int date = 0;
//			date = is.read();
//			if (fileName.equalsIgnoreCase(RC950_upgrade_fileName)) {
//				if (49 == date)// "1"��ascii��Ϊ49
//				{
//					res = "ok";
//				} else {
//					res = "error";
//				}
//			}
//			is.close();
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//		return res;
//	}
	// linxp add for upgrade RC950 dongle end 2013-08-23

	// //////----------End of File--------
}