package com.tcl.factory.view;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import android.app.Dialog;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.SystemProperties;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import com.tcl.customerapi.R;
import com.tcl.devicemanager.EnumSleepTimeState;
import com.tcl.factory.FactoryManager;
import com.tcl.factory.bsp.TCL;
import com.tcl.factory.bsp.TV;
import com.tcl.factory.bsp.TVDefine;
import com.tcl.factory.commands.FactoryCommands;
import com.tcl.factory.def.DEFS;
import com.tcl.factory.impl.FactoryCommandsListener;
import com.tcl.factory.ir.IRManager;
import com.tcl.factory.ir.IRManagerListener;
import com.tcl.factory.ir.IRReceiver;
import com.tcl.factory.thirdparty.ThirdParty;

public class InfoService extends Service {
	
	private final static String TAG = "InfoService";
	
	public static InfoService _Instance = null;
	private static boolean infoServiceVisible = true;
	private static boolean setverWorking=false;
	private static boolean bluetoothScaning=false;
	private int indexProjectID = 0;
	
	private ImportantNotifiIconDialog mDialog;
	private  final int CLOSE_PROGRESS_WINDOW = 1;
	private  final int REFRESH_WINDOW = 3;
	private int secondCount=0;
	private TextView dpMode=null;
	private TextView mv=null;
	private TextView sv=null;
	private TextView tconVer=null;
	private TextView projectId=null;
	private TextView panelId=null;
	private TextView memc = null;
	private TextView mid=null;
	private View infoView=null;
	private IRReceiver mIRReceiver = null;
	FactoryCommands factoryCommands ;
	FactoryCommandsListener factoryCommandsListener;

	//鍒锋柊P/D/S
	private ScheduledExecutorService execService = Executors.newScheduledThreadPool(1);
	private ScheduledExecutorService btScanService = Executors.newScheduledThreadPool(1);
	private BluetoothAdapter mAdapter = BluetoothAdapter.getDefaultAdapter();
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			secondCount++;
			switch (msg.what) {

			case CLOSE_PROGRESS_WINDOW:
				if ((mDialog != null) && mDialog.isShowing()) {
					mDialog.dismiss();
					Log.v(TAG, "=====Close Toast");
				}
				break;
			case REFRESH_WINDOW:
				if(infoServiceVisible){
					infoUpdate(secondCount);
					
					// add by wangst,20150602.鎵撳紑P妯�?�紡,榛樿涓嶅搷搴旂潯鐪犲叧鏈�
					if(EnumSleepTimeState.E_OFF != ThirdParty.mTimerManager.getSleepMode()){
						Log.d(TAG, "cancelPoweroffTimer");
						ThirdParty.mTimerManager.setSleepMode(EnumSleepTimeState.E_OFF);
						ThirdParty.mTimerManager.cancelPoweroffTimer();
						SystemProperties.set("sys.sleepmode","0"); // 璁剧疆鐫＄湢妯�?�紡涓�"鍏�",MS828鎻愬嚭璁剧疆閲岄潰鐫＄湢涓嶄负鍏崇殑闂�?
					}
				}
				break;
			}
		}
	};
	public static Handler serialAndKeyHandler = new Handler() 
	{
		public void handleMessage(Message msg) 
		{
			Log.d(TAG, "handleMessage what ="+msg.what);
			int cmd_data = msg.arg1;
			int keyCode = msg.arg2;
//			Toast.makeText(ThirdParty.mContext, "kode="+cmd_data+"__"+keyCode, 3000).show();
			switch (msg.what) {
			case 0:
				 IRManager.parserSerial(cmd_data,keyCode);
				break;
			case 1:
				IRManagerListener.parserEvent(cmd_data,keyCode);
				break;
			}
			Log.v(TAG, "[handleMessage]IN");
			super.handleMessage(msg);
		}
	};
	
	private Handler serialHandler = new Handler() 
	{
		public void handleMessage(Message msg) 
		{
			Log.v(TAG, "[handleMessage]IN");
//			SerialManager.serialCmdVerify(DEFS.receiveData);	
//			DEFS.dataComing=false;
			super.handleMessage(msg);
		}
	};
	@Override
	public void onStart(Intent intent, int startId) {
		// TODO Auto-generated method stub
		Log.v(TAG, "[onStart] wst");
		if(!setverWorking)
		{
			if(intent == null)
				return;
			int mode=intent.getIntExtra("mode", 0);
			
			Log.v(TAG, "[onStart]startId/mode:"+startId+"/"+mode);
			_Instance = this;
			
			TCL.implemetThirdPartyIsntance(this);
			UIInit();
			setverWorking=true;
			DEFS.DebugLevel = 4;
			
			addListener();
//			registerBroadcast();						
			if(mode == 1){
				TV.writeS(TVDefine.PMode, DEFS.Enable);
			}
			ThirdParty.broadCastPmodeStatus();
			if(ThirdParty.getPModeStatus()) {
				ThirdParty.setSTRstatus(false);
				ThirdParty.setWakeLockStatus(true);
				SystemProperties.set("persist.P_MODE", "1");
				//new task for bluetoothScan
				//mAdapter.setScanMode(BluetoothAdapter.SCAN_MODE_CONNECTABLE);  //��������Ϊɨ��ģʽ   ���ɱ������豸����  ������������豸���
				bluetoothScaning = true;
				execService.scheduleAtFixedRate(new BluetoothScan(), 100, 20000, TimeUnit.MILLISECONDS); //ɨ������Ϊ20�룬ÿ��ɨ�����12��				
			}
			else{
				ThirdParty.setWakeLockStatus(false);
				SystemProperties.set("persist.P_MODE", "0");
	            ThirdParty.setRootSeek("rm -Rf /data/property/persist.P_MODE");
			}
			Log.v(TAG, "onStart setverWorking");
		}
	}

	private void registerBroadcast()
	{
		Log.v(TAG, "[registerBroadcast]");
		mIRReceiver = new IRReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction("com.tcl.factory.ir");
		filter.addAction("com.tcl.factory.Serial");
		filter.addCategory("android.intent.category.DEFAULT");
		this.registerReceiver(mIRReceiver, filter);
	}
	
	private void unregisterBroadcast()
	{
		Log.v(TAG, "[unregisterBroadcast]");
		unregisterReceiver(mIRReceiver);
	}
	
	private void UIInit(){
		Log.v(TAG, "[UIInit]");
		mDialog = new ImportantNotifiIconDialog(this,
				android.R.style.Theme_Light_Panel);
		Window window = mDialog.getWindow();
		WindowManager.LayoutParams lp = window.getAttributes();
		lp.token = null;
		lp.type = WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG;

		lp.gravity =Gravity.CENTER;
		lp.x=(int) (-DEFS.DESKTOP_WIDTH*0.46);
		lp.y=(int) (DEFS.DESKTOP_HEIGHT*0.35);
		//淇敼schedule鐨勬墽琛屾柟寮忎负scheduleExecutorService,浣跨敤鏃堕棿涓虹浉�?�规椂闂�?,閬垮厤鍒囨崲淇℃簮杩囩▼涓�,缁濆鏃堕棿鍙戠敓鏀瑰彉瀵艰嚧infoservice鐨凾imerTask鍋滄鎵ц�?
		execService.scheduleAtFixedRate(new MyTimerTask(), 100, 2000, TimeUnit.MILLISECONDS);
		
		window.setAttributes(lp);
		window.addFlags(android.view.WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | 
						android.view.WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL |
						android.view.WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH);
		infoView = View.inflate(this, R.layout.fac_infodisplay, null);

		mDialog.setContentView(infoView);
		dpMode =(TextView) infoView.findViewById(R.id.dpMode);
		mv =(TextView) infoView.findViewById(R.id.mv);
		sv =(TextView) infoView.findViewById(R.id.sv);
		tconVer =(TextView) infoView.findViewById(R.id.tcon_version);
		mid =(TextView) infoView.findViewById(R.id.mid);
		projectId =(TextView) infoView.findViewById(R.id.project_id);
		panelId =(TextView) infoView.findViewById(R.id.panel_id);
		memc =(TextView) infoView.findViewById(R.id.memc_version);
		mDialog.show();

		infoView.setVisibility(View.VISIBLE);
	}
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		
		Log.v(TAG,"[onDestroy]");
		
		if( TV.readS(TVDefine.PMode)==DEFS.Disable) {
			if(DEFS.Enable==DEFS.uartOpenStatus)
				TV.writeS(TVDefine.Serial, DEFS.Disable);
		}
		ThirdParty.broadCastPmodeStatus();
		ThirdParty.setWakeLockStatus(false);
//		unregisterBroadcast();
		removeListener();
		if ((mDialog != null) && mDialog.isShowing()) {
			mDialog.dismiss();
			
		}
		setverWorking = false;
		execService.shutdown();
		execService = null;
		btScanService.shutdown();
		btScanService = null;
		super.onDestroy();
	}



	private class MyTimerTask extends TimerTask{
		@Override
		public void run() {
			if( TV.readS(TVDefine.PMode)==DEFS.Enable) {
				if(DEFS.Disable==DEFS.uartOpenStatus)
					TV.writeS(TVDefine.Serial, DEFS.Enable);
				if(bluetoothScaning == false)
				{
					bluetoothScaning = true;				
					//mAdapter.setScanMode(BluetoothAdapter.SCAN_MODE_CONNECTABLE);  //��������Ϊɨ��ģʽ   ���ɱ������豸����  ������������豸���
					btScanService.scheduleAtFixedRate(new BluetoothScan(), 100, 20000, TimeUnit.MILLISECONDS); //ɨ������Ϊ20�룬ÿ��ɨ�����12��
				}			
			}
			else {
				if(DEFS.Enable==DEFS.uartOpenStatus)
					TV.writeS(TVDefine.Serial, DEFS.Disable);
			}
			
			handler.sendEmptyMessage(REFRESH_WINDOW);
		}
	}
	private class BluetoothScan extends TimerTask{
		public void run(){ 
			if( TV.readS(TVDefine.PMode)==DEFS.Enable) {
			if (!mAdapter.isEnabled())
				{
					mAdapter.enable();
				}
			if(mAdapter.isDiscovering())
				{
					mAdapter.cancelDiscovery();
				}
			mAdapter.startDiscovery();
	        }
		}
		}
	private class ImportantNotifiIconDialog extends Dialog {

		public ImportantNotifiIconDialog(Context context, int theme) {
			super(context, theme);
			// TODO Auto-generated constructor stub
		}

		@Override
		protected void onCreate(Bundle savedInstanceState) {
			// TODO Auto-generated method stub
			super.onCreate(savedInstanceState);
		}
	}

	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		Log.v(TAG, "[onBind]");
		UIInit();
		return null;
	}

	public void	infoUpdate(int secondCount){
		if(secondCount%3==1){
			infoView.setVisibility(View.INVISIBLE);		
		}
		else
		{
			infoView.setVisibility(View.VISIBLE);
			return;
		}
	
		String dpModeStr="";
		if( TV.readS(TVDefine.DMode)==DEFS.Enable)
			dpModeStr=dpModeStr+"D";
		if( TV.readS(TVDefine.PMode)==DEFS.Enable)
		{ dpModeStr=dpModeStr+"P";
		   if(ThirdParty.getSerialDebugStatus())
			dpModeStr=dpModeStr+"S";
		}
		
		if(dpModeStr==""){
			dpMode.setText("");
			mv.setText("");
			sv.setText("");
			tconVer.setText("");
			mid.setText("");
			projectId.setText("");
			panelId.setText("");
			memc.setText("");
		}
		else{
			dpMode.setText(dpModeStr);
			mv.setText("MV:  "+ThirdParty.getSoftwareVersion());
			sv.setText("SV:  "+ThirdParty.getBootcodeVersion());
			if(ThirdParty.getTconVersion()==null)
			{
				tconVer.setText("Tcon version: null");
			}
			else{
				tconVer.setText(ThirdParty.getTconVersion());
			}
			indexProjectID = ThirdParty.getProjectIDValue();
			if(indexProjectID<10)
				projectId.setText("ID:  "+"00"+indexProjectID);
			else if(indexProjectID<100)
				projectId.setText("ID:  "+"0"+indexProjectID);		
			else if(indexProjectID>=100){
				projectId.setText("ID:  "+indexProjectID);
			}
			if(ThirdParty.isSupportPanelID()){
				panelId.setText("PanelID:  " + ThirdParty.getPanelIDValue());
			}else {
				panelId.setText("PanelID: N/A");
			}
			
			memc.setText("MEMC:  " + ThirdParty.getFrcCodeVersion());				
			mid.setText("MID:  " + gerMidStr());
		}
	}
	
	private String gerMidStr() {
		StringBuffer midstr = new StringBuffer();
		boolean hasOne = false;
		boolean hasMac = hasMac();
		boolean hasDid = hasDid();
		boolean hasSn = hasSN();
		boolean hasRCode = hasRegisterCode();
		boolean hasDrm = hasDRM();
		if(hasMac) {
			midstr.append("MAC");
			hasOne = true;
		}
		if(hasDid) {
			if(hasOne) {
				midstr.append(" & DID");
			} else {
				midstr.append("DID");
				hasOne = true;
			}
		}
		if(hasSn) {
			if(hasOne) {
				midstr.append(" & SN");
			} else {
				midstr.append("SN");
				hasOne = true;
			}
		}
		if(hasRCode) {
			if(hasOne) {
				midstr.append(" & RegisterCode");
			} else {
				midstr.append("RegisterCode");
				hasOne = true;
			}
		}
		if(ThirdParty.hasHDCP()) {
			if(hasOne) {
				midstr.append(" & HDCP");
			} else {
				midstr.append("HDCP");
				hasOne = true;
			}
		}
		if(ThirdParty.hasWIDI()) {
			if(hasOne) {
				midstr.append(" & WIDI");
			} else {
				midstr.append("WIDI");
				hasOne = true;
			}
		}
		if(ThirdParty.hasCI()){
			if(hasOne) {
				midstr.append(" & CI");
			} else {
				midstr.append("CI");
				hasOne = true;
			}
		}
		if(hasDrm){
			if(hasOne) {
				midstr.append(" & DRM");
			} else {
				midstr.append("DRM");
				hasOne = true;
			}
		}
		if(ThirdParty.hasWideVine()){
			if(hasOne) {
				midstr.append(" & WideVine");
			} else {
				midstr.append("WideVine");
				hasOne = true;
			}
		}
		if(!hasOne) {
			midstr.append("NULL");
		}
		return midstr.toString();
	}
	
	private boolean hasDRM() {
		return ThirdParty.hasDRM();
	}

	private boolean hasMac() {
		String mac = ThirdParty.getMACAddressString();
		return isNull(mac);
	}
	
	private boolean hasSN() {
		String sn = ThirdParty.getSNString();
		return isNull(sn);
	}
	
	private boolean hasRegisterCode() {
		String recode = ThirdParty.getRegiterCodeString();
		return isNull(recode);
	}
	
	private boolean hasDid() {
		String did = ThirdParty.getDeviceIDString();
		return isNull(did);
	}
	
	private boolean isNull(String str) {
		if(str == null || str.trim().equals("") || str.trim().equalsIgnoreCase("null")) {
			return false;
		} else {
			return true;
		}
	}
	
	private String rsStatus[] = {"NG", "OK", "NG"};
	
	private void addListener()
	{
		Log.v(TAG, "[addListener]");
//		SerialUtils.getInstance().addListener(new SerialUtils.UiSerialListener()
//		{
//			public void onChange() 
//			{
//				Log.v("TAG", "[UiSerialListener][onChange]IN");
//				Message message=Message.obtain();
//				serialHandler.sendMessage(message);
//			}
//		});
//		FactoryCommandsImpl.getInstance().addListener(new FactoryCommandsListener());
		// start lyf
		
		factoryCommands = FactoryManager.getInstance(this).getFactoryCommands();
		factoryCommandsListener = new FactoryCommandsListener();
		Log.d(TAG, " addListener factoryCommandsListener = "+factoryCommandsListener);
		factoryCommands.addListener(factoryCommandsListener);
		// end lyf
	}
	private void removeListener(){
		if(factoryCommandsListener!=null){
			factoryCommands.removeListener(factoryCommandsListener);
		}
	}
	
	public void setVisibility(boolean visibility)
	{
		infoServiceVisible = visibility;
		if(visibility) {
			infoView.setVisibility(View.VISIBLE);
		}
		else {
			infoView.setVisibility(View.INVISIBLE);
		}
	}

}
