package com.tcl.factory.bsp;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.channels.FileChannel;
import java.util.List;

import android.app.ActivityManager;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

import com.tcl.devicemanager.WifiMultiSupport;
import com.tcl.factory.def.DEFS;
import com.tcl.factory.thirdparty.ThirdParty;
import com.tcl.factory.utils.Debug;
import com.tcl.factory.utils.TestDeviceID;
import com.tcl.factory.utils.Utils;
import com.tcl.factory.view.DialogHint;
import com.tcl.factory.view.FrontPanelKeyTest;
import com.tcl.factory.view.InfoService;
import com.tcl.factory.view.MainMenu;
import com.tcl.factory.view.TestPattern;
import com.tcl.media.TMediaPlayer;
import com.tcl.tvmanager.vo.EnTCLInputSource;
 

public class TCL {

	private static String TAG = "TCL";

	private int sourcetype=0;
	private static boolean LDrunning = false;
	public static Context mContext = null;
	public static DialogHint dialogHint = null;
	static short buffer[]=null;
//	private static MediaPlayer mMediaPlayer=null;
	private static int tunnerMode = DEFS.TYPE_DVBC;//jane add
	private final static String ACCESS_KEY="CUHddI7z0MEjoYM+pzBDE1/isVCXbHqE763VcUkjFeJbMvxxBjHcyN14vNM3ziK5UqlLv/AgQ2yWovKV3yD8uG2XDfgdPXVrjSaBMLTuyVzMv6sO44LHIP685Q8tG+nhCDFYRZUTzTdlj7r//HsrJtVI0GygqV0C0IRaPacOOZQzbTmYD+U0GnrC4UWnFmZKRx5q6h5baMcfFPZaGGEIM+mCZ71drqNoio0CBa4M6RJt9xaUZXl/Ibu2Lei2CIAJZhTdV1FYEbOTgHQCfnXTLm/uADHMtAkZUdzBEIo1RD+uvTd37EfRtcpY8H/EU3XUkXqOg8cHSlKIPdOSqR4Ynw==";
	public static void implemetThirdPartyIsntance(Context context)
	{
		if(mContext != null)//longchao add
			return;
		mContext = context;
		Utils.mContext=context;
		new ThirdParty(mContext);
	}
	public static short getBluetooth3DDeviceID()
	{
		String mac = BluetoothAdapter.getDefaultAdapter().getAddress();
		Debug.v(TAG, "[getBluetooth3DDeviceID]mac = "+mac);
		return 0;
	}
//	public static short getBluetooth3DStatus()
//	{
//		BluetoothAdapter.getDefaultAdapter().getBondedDevices();
//	}
//	public static short getBluetooth3DSyncStatus()
//	{
//		BluetoothAdapter.getDefaultAdapter().getBondedDevices();
//	}
	public static boolean getSDCardStatus()
	{
		File file = new File(DEFS.SDCardPath);
		String state = Environment.getExternalStorageState();
		if (file.exists() && state.equals(Environment.MEDIA_MOUNTED))  
			return true;
		else
			return false;
	}
	
	public static boolean getUSBStatus() 
	{  
		Process process = null; 
		try {
			process = Runtime.getRuntime().exec("mount");
			BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
			String line = "";
			while ((line = input.readLine()) != null) { 
				Debug.v(TAG, "getUSBStatus Line is "+line);
				if(line.indexOf("/dev/block/vold/")>=0) {
					if(line.indexOf("/mnt/usb/")>0) {
						return true;
					}
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		return false;
	}
	public static synchronized String getUSBMountPath(Context context)
	{  
		//catch mount info into temp.txt
		Debug.v(TAG, "getUSBMountPath");
		ThirdParty.setRootSeek("cat /proc/mounts > /tmp/tmp.txt");
		ThirdParty.setRootSeek("chmod 777 /tmp/tmp.txt");
		//open temp.txt and cover info into String
		String mount_info = null;
		String pathName = "/tmp/";
		String fileName = "tmp.txt";
		Debug.v(TAG, "filePath = " + pathName + fileName);
		File mount_info_file = new File(pathName,fileName);
		try {
			FileReader fr = new FileReader(mount_info_file);
			BufferedReader br = new BufferedReader(fr);
			while((mount_info = br.readLine()) != null)
			{
				//if String contains /dev/block/vold/ , return usbpath
				if(mount_info.contains("/dev/block/vold/"))
				{
					Debug.v(TAG, "mount_info = " + mount_info);
					String[] tmp_string = mount_info.split(" ");
					for (String UsbPath : tmp_string) {
						if(UsbPath.startsWith("/mnt"))
						{
							Debug.v(TAG, "UsbPath = " + UsbPath);
							br.close();
							fr.close();
							ThirdParty.setRootSeek("rm -rf /tmp/tmp.txt");
							return UsbPath;
						}
					}	
				}
			}
			br.close();
			fr.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "";
	}

	public static void CIKeyUpgrade(){
		String path = getUSBMountPath(mContext);
		if(null==path || ("".equals(path)) ){
			Toast.makeText(mContext, "NO_USB_MOUNT", Toast.LENGTH_SHORT).show();
			return;
		} else {
			boolean result = ThirdParty.CIKeyUpgrade();
			if (result) {
				Toast.makeText(mContext, "CI Upgrade OK",
						Toast.LENGTH_SHORT).show();
			} else {
				Toast.makeText(mContext, "CI Upgrade Fail",
						Toast.LENGTH_SHORT).show();
			}
		}
	}
	
	public static void WideVineKeyUpgrade(){
		String path = getUSBMountPath(mContext);
		if(null==path || ("".equals(path)) ){
			Toast.makeText(mContext, "NO_USB_MOUNT", Toast.LENGTH_SHORT).show();
			return;
		} else {
			boolean result = ThirdParty.WideVineKeyUpgrade();
			if (result) {
				Toast.makeText(mContext, "WideVineKey Upgrade OK",
						Toast.LENGTH_SHORT).show();
			} else {
				Toast.makeText(mContext, "WideVineKey Upgrade Fail",
						Toast.LENGTH_SHORT).show();
			}
		}
	}
	
	
	public static void HdmiKeyUpgrade() {
		String path = getUSBMountPath(mContext);
		if(null==path || ("".equals(path)) ){
			Toast.makeText(mContext, "NO_USB_MOUNT", Toast.LENGTH_SHORT).show();
			return;
		} else {
			boolean result = ThirdParty.HdmiKeyUpgrade();
			if (result) {
				Toast.makeText(mContext, "HDCP Upgrade OK",
						Toast.LENGTH_SHORT).show();
			} else {
				Toast.makeText(mContext, "HDCP Upgrade Fail",
						Toast.LENGTH_SHORT).show();
			}
		}
	}

	public static void WidiKeyUpgrade() {
		String path = getUSBMountPath(mContext);
		if(null==path || ("".equals(path)) ){
			Toast.makeText(mContext, "NO_USB_MOUNT", Toast.LENGTH_SHORT).show();
			return;
		} else {
			boolean result = ThirdParty.WidiKeyUpgrade();
			if (result) {
				Toast.makeText(mContext, "HDCP_2 Upgrade OK",
						Toast.LENGTH_SHORT).show();
			} else {
				Toast.makeText(mContext, "HDCP_2 Upgrade Fail",
						Toast.LENGTH_SHORT).show();
			}
		}
	}

	public static void VB1_LVDS_Upgrade() {
		String path = getUSBMountPath(mContext);
		if(null==path || ("".equals(path)) ){
			Toast.makeText(mContext, "NO_USB_MOUNT", Toast.LENGTH_SHORT).show();
			return;
		} else {
			boolean result = ThirdParty.VB1_LVDS_Upgrade();
			if (result) {
				Toast.makeText(mContext, "VB1_TO_LVDS Upgrade OK",
						Toast.LENGTH_SHORT).show();
			} else {
				Toast.makeText(mContext, "VB1_TO_LVDS Upgrade Fail",
						Toast.LENGTH_SHORT).show();
			}
		}
	}
	
	public static boolean FPCImageUpgrade() {
		String path = getUSBMountPath(mContext);
		if(null==path || ("".equals(path)) ){
			Toast.makeText(mContext, "NO_USB_MOUNT", Toast.LENGTH_SHORT).show();
			return false;
		} else {
			boolean result = ThirdParty.FPCImageUpgrade();
			return result;
		}
//		Debug.v(TAG, "USB2NVM : " + value);
	}
	
	public static int getFPCImageUpgradeProgress() {
		return ThirdParty.getFPCImageUpgradeProgress();
	}
	
	public static void MACUpgrade() {
		String path = getUSBMountPath(mContext);
		if(null==path || ("".equals(path)) ){
			Toast.makeText(mContext, "NO_USB_MOUNT", Toast.LENGTH_SHORT).show();
			return;
		} else {
			boolean result = ThirdParty.MACUpgrade();
			if (result) {
				Toast.makeText(mContext, "MAC Upgrade OK",
						Toast.LENGTH_SHORT).show();
			} else {
				Toast.makeText(mContext, "MAC Upgrade Fail",
						Toast.LENGTH_SHORT).show();
			}
		}
	}
	
	public static boolean getWiredNetStatus() {
		ConnectivityManager connec = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connec == null)
			return false;
		boolean eth = false;
		connec.getAllNetworkInfo();
		NetworkInfo allinfo = connec.getNetworkInfo(9);
		if (allinfo != null) {
			if (allinfo.isConnected()) {
 				eth = true;
			} else
 				eth = false;
		} else
 			eth = false;
		boolean pppoe = false;
		NetworkInfo pppoeinfo = connec.getNetworkInfo(8);
		if (pppoeinfo != null) 
		{
			if (pppoeinfo.isConnected()) 
			{
 				pppoe = true;
			} else
 				pppoe = false;
		} 
		else
 			pppoe = false;
		if (!eth && !pppoe) 
		{
 			return false;
		} else 
		{
 			return true;
		}
	}
	 
	public static boolean getWifiStatus() 
	{
		ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (cm == null)
			return false;
		NetworkInfo[] info = cm.getAllNetworkInfo();
		if (cm == null || info == null) 
 			return false;
		for (int i = 0; i < info.length; i++) 
		{
			if (info[i].getType() == ConnectivityManager.TYPE_WIFI) 
			{
				if (info[i].getState() == NetworkInfo.State.CONNECTED) 
					return true;
				else
					return false;
 			}
		}
		return false;
	}

	public static boolean getNetworkConnectivityStatus()
	{
		ConnectivityManager manager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkinfo = manager.getActiveNetworkInfo();
		if(networkinfo==null)
			return false;
		return  networkinfo.isAvailable();		
	}
	
	public static void getPcLinkStatus(boolean uartComond) {
		
		if (!uartComond) {
			Toast.makeText(mContext, "PC Linking test success!!", Toast.LENGTH_SHORT).show();	
		}		
	}
	
	public static boolean getDeviceIDShortTestStatus( ) {
 		TestDeviceID mTestDevice = new TestDeviceID(mContext);		 
		return mTestDevice.getTestDeviceStatus();
	}
	 
//	public static void setSerialDebugStatus(boolean status) 
//	{
//		DEFS.serialDebugStatus = status;
//		Debug.v(TAG, "setSerialDebugStatus : " +status );
//	}
//	public static boolean getSerialDebugStatus( ) 
//	{  
//		return DEFS.serialDebugStatus;
//	}

 
	
	public static short[] getUSBCloneStatus()
	{
		short[] status = new short[2];
		switch (DEFS.clone_result) {
		case DEFS.NVM_TO_USB_FAIL:
			status[0] = 0x00;
			status[1] = 0x00;
			break;
		case DEFS.NVM_TO_USB_OK:
			status[0] = 0x00;
			status[1] = 0x01;
			break;
		case DEFS.USB_TO_NVM_FAIL:
			status[0] = 0x01;
			status[1] = 0x00;
			break;
		case DEFS.USB_TO_NVM_OK:
			status[0] = 0x01;
			status[1] = 0x01;
			break;
		}
		return status;
	}
	
	public static boolean getTestPatternStatus() {
		return DEFS.TestPatternStatus;
	}
	
	public static void setTestPatternStatus(boolean status) {
		DEFS.TestPatternStatus = status;

		if (!status) {
			Toast.makeText(mContext, "Pannel Mode Test Disable", Toast.LENGTH_SHORT).show();
			stopTestPattern();
			setInfoDisServiceVisible(true);
		} else {
			Toast.makeText(mContext, "Pannel Mode Test Enable", Toast.LENGTH_SHORT).show();	
			startTestPattern();
			setInfoDisServiceVisible(false);
		}
	}
	public static void startTestPattern()
	{	//goto TestPattern
		Intent mIntent = new Intent();
		mIntent.setClass(mContext, com.tcl.factory.view.TestPattern.class);
		mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		mContext.startActivity(mIntent);
	}
	public static void stopTestPattern()
	{
		if(TestPattern._Instance!=null) {
			TestPattern._Instance.finish();
		}
	}
	public static void setTestPatternColor(int colorIDIndexTable_index)
	{
		if(TestPattern._Instance!=null) {
			TestPattern._Instance.setTestPatternColor(colorIDIndexTable_index);
		}
	}	
	public static boolean getKeyCodeTestStatus() {
		return DEFS.KeyCodeTestStatus;
	}
	public static void setKeyCodeTestStatus(boolean status) 
	{
		DEFS.KeyCodeTestStatus = status;
		if (!status) {
			stopFrontPanelKeyTest();
			ThirdParty.setPowerKeyPassToApp(DEFS.Disable);
		} else {
			startFrontPanelKeyTest();
			ThirdParty.setPowerKeyPassToApp(DEFS.Enable);
		}
 	}
	public static void startFrontPanelKeyTest()
	{	//goto TestPattern
		Intent mIntent = new Intent();
		mIntent.setClass(mContext, com.tcl.factory.view.FrontPanelKeyTest.class);
		mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		mContext.startActivity(mIntent);
	}
	public static void stopFrontPanelKeyTest()
	{
		if(FrontPanelKeyTest._Instance!=null) {
			FrontPanelKeyTest._Instance.finish();
		}
	}



	private static void startWarmUp() 
	{
		Debug.v(TAG, "startWarmUp");
		//DEFS.warmupStatus = DEFS.Enable;
		ThirdParty.setWModeStatus(DEFS.Enable);
		//MainMenu.mainArea.setVisibility(View.INVISIBLE);
		Intent mIntent = new Intent();
		mIntent.setClass(mContext, com.tcl.factory.view.WarmUp.class);
		mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		mContext.startActivity(mIntent);
	}
	private static void stopWarmUp() 
	{
		//DEFS.warmupStatus = DEFS.Disable;
		ThirdParty.setWModeStatus(DEFS.Disable);
		//MainMenu.mainArea.setVisibility(View.VISIBLE);
	}
	
	public static void setWarmUpStatus(boolean status)
	{
		if(status == DEFS.Enable)
			startWarmUp();
		else if(status == DEFS.Disable)
			stopWarmUp();
	}
	
	public static short[] getWarmUPTimeData() 
	{
		return DEFS.WarmUPTime;
	}
	 
	public static short[] getPlatformTypeData() 
	{
		char[] sw = getDeviceModel().toCharArray();
		short[] swByte = new short[sw.length];
		for (int i = 0; i < sw.length; i++) 
		{
			swByte[i] = (short) sw[i];
		}
		return swByte;
	}
	
	
	public static String getDeviceModel() 
	{
		return ThirdParty.getClientType();
	}
	
	public static int getHotelVolumeMaxValue()
	{
//		SystemProperties.set("service.facHotelMaxVol", ""+maxVolume);
		return ThirdParty.mFactoryAdapter.getHotelVolumeMax();
	}
	public static void setHotelVolumeMaxValue(int maxVolume)
	{
//		SystemProperties.set("service.facHotelMaxVol", ""+maxVolume);
		ThirdParty.mFactoryAdapter.setHotelVolumeMax(maxVolume);
	}
	
	public static void setOverscan(int type,int value)
	{
		switch(type) {
		case 0:
			ThirdParty.setHorizonPosition(value);
			break;
		case 1:
			ThirdParty.setHorizonZoomSize(value);
			break;
		case 2:
			ThirdParty.setVerticalPosition(value);
			break;
		case 3:
			ThirdParty.setVerticalZoomSize(value);
			break;
		}
	}
	public static int getOverscan(int type)
	{
		int value = 0;
		
		switch(type) {
		case 0:
			value = ThirdParty.getHorizonPosition();
			break;
		case 1:
			value = ThirdParty.getHorizonZoomSize();
			break;
		case 2:
			value = ThirdParty.getVerticalPosition();
			break;
		case 3:
			value = ThirdParty.getVerticalZoomSize();
			break;
		}
		return value;
	}
	

	public static void usbUpgrade()
	{
		//Utils.intentHandler(DEFS.Package_TCL_upgrade, DEFS.Activity_Package_TCL_upgrade );
		Intent mIntent = new Intent();
		mIntent.setAction("android.tcl.mtk.MaualUpdate");
		//mIntent.setClassName("com.tcl.mtk.mtkVersionUpdate","com.tcl.mtk.mtkVersionUpdate.UI.UpdateActivity");
		//mIntent.putExtra("ACTIONTYPE", 1);
		mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		mContext.startActivity(mIntent);
	}	
	
	public static boolean isTopActivity(String $packageName) 
	{
	    //_context鏄竴涓繚瀛樼殑涓婁笅锟�?
	    ActivityManager __am = (ActivityManager) mContext.getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
	    List<ActivityManager.RunningAppProcessInfo> __list = __am.getRunningAppProcesses();
	    if(__list.size() == 0) return false;
	    for(ActivityManager.RunningAppProcessInfo __process:__list)
	    {
	        if(__process.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND &&
	                __process.processName.equals($packageName))
	        {
	            return true;
	        }
	    }
	    return false;
	} 


	public static void setSerInfoShowEnable(boolean status)
	{
		if(DEFS.Enable==status) {
			Intent it = new Intent();
			it.putExtra("select", DEFS.S_MODE);
			it.putExtra("osdlabel",DEFS.OSD_SHOW);
			it.setClassName("com.tcl.factory.view","com.tcl.factory.view.MainMenu");
			it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//Jane add
			mContext.startActivity(it);
		}
		else {
			if(MainMenu._Instance!=null) {
				MainMenu._Instance.finish();
			}
		}
	}
	public static void setFacInfoShowEnable(boolean status)
	{
		if(DEFS.Enable==status) {
			Intent it = new Intent();
			it.putExtra("select", DEFS.P_MODE);
			it.putExtra("osdlabel",DEFS.OSD_SHOW);
			it.setClassName("com.tcl.factory.view","com.tcl.factory.view.MainMenu");
			it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//Jane add
			mContext.startActivity(it);
		}
		else {
			if(MainMenu._Instance!=null) {
				MainMenu._Instance.finish();
			}
		}
	}
	
	public static void setInfoDisServiceEnable(boolean status)
	{
		Debug.v(TAG,"[setInfoDisServiceEnable]:"+status);
		if(DEFS.Enable==status) {
	
			Intent it = new Intent();
			it.setClassName("com.tcl.factory.view","com.tcl.factory.view.InfoService");
			it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//Jane add
			it.putExtra("mode", 0);
			mContext.startService(it);
		}
		else {
			Intent it = new Intent();
			it.setClassName("com.tcl.factory.view","com.tcl.factory.view.InfoService");
			it.putExtra("mode", 0);
			mContext.stopService(it);
		}
	}
	
	public static void setInfoDisServiceVisible(boolean status)
	{
		if(InfoService._Instance!=null) {
			InfoService._Instance.setVisibility(status);
		}
	}
	public static void systemReboot() 
	{  
		Process process = null; 
		try {
			process = Runtime.getRuntime().exec("reboot");

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return ;
	}
	
	public static int writeTVStorageFile(String name,int addr, byte[] data, int len)
	{
		int ret = 0;
		// new file
		try{
			        
			File file = new File(name);
			if(!file.exists()){
				byte[] tmp_buffer = new byte[4*1024];
				int tmp_len = 4*1024;
				file.createNewFile();
				file.setReadable(true, false);
				file.setWritable(true, false);
				FileOutputStream fout = new FileOutputStream(file);
				FileChannel fileChannel = fout.getChannel();
				fout.write(tmp_buffer, 0, tmp_len);
//				fout.getChannel().truncate(4*1024);
				fout.flush();
				fout.close();
				Debug.v(TAG, "new file:"+file.getAbsolutePath());
			}
		}catch(Exception e){
			e.printStackTrace();         
		}
		
		// write
		try{
			if(data.length<len)len=data.length;
			File file = new File(name);
			FileOutputStream fout = new FileOutputStream(file);
			fout.getChannel().position(addr);
			
			fout.write(data, 0, len);
			fout.flush();
			fout.close();
			ret = len;
			Debug.v(TAG, "write:"+data[0]);
        } catch(Exception e){
			e.printStackTrace();
		}
		
        return ret;
	}
	public static int readTVStorageFile(String name,int addr, byte[] data, int len)
	{
		int ret = 0;
		
		// new file
		try{
	        File file = new File(name);
			if(!file.exists()){
				byte[] tmp_buffer = new byte[4*1024];
				int tmp_len = 4*1024;
				file.createNewFile();
				file.setReadable(true, false);
				file.setWritable(true, false);
				FileOutputStream fout = new FileOutputStream(file);
				FileChannel fileChannel = fout.getChannel();
				fout.write(tmp_buffer, 0, tmp_len);
//				fout.getChannel().truncate(4*1024);
				fout.flush();
				fout.close();
				Debug.v(TAG, "new file:"+file.getAbsolutePath());
			}
		}catch(Exception e){
			e.printStackTrace();         
		}
		
		// read
		try{
			if(data.length<len)len=data.length;
			File file = new File(name);

			FileInputStream fin = new FileInputStream(file);
			fin.getChannel().position(addr);
			fin.read(data,0,len);
			fin.close();
			ret = len;
			Debug.v(TAG, "read:"+data[0]);
		}catch(Exception e){ 
			e.printStackTrace();         
		}
        return ret;
	}
	public static void readEepromTest()
	{
		// 杩橀渶鎵緁1瀵规帴
//		byte[] buf = new byte[4096];
//		for(int i=0;i<4096;i++)
//			buf[i]=(byte)ThirdParty.getStorageValue(i);
//		TCL.writeTVStorageFile("/tmp/e.bin",0,buf,4096);
//		
//		String path=getUSBMountPath();
//		if(path.length()>9) {
//			try {
//				String cmd = "cp /tmp/e.bin "+ path+"/readEepromTest_4096.bin";
//				Process process = Runtime.getRuntime().exec(cmd);
//				Toast.makeText(mContext, "EEPROM_TO_USB_OK:", Toast.LENGTH_SHORT).show();
//			} catch (IOException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//		}
	}

	
	public static void setWiFiPower(int status) {
		WifiManager wifiManager = (WifiManager)mContext.getSystemService(mContext.WIFI_SERVICE);
	    if(status==DEFS.COMMON_ON)
		{
		    wifiManager.setWifiEnabled(true);
		    int count=0;
		   while( wifiManager.getWifiState()!=WifiManager.WIFI_STATE_ENABLED){
			   try {
				Thread.sleep(20);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			   count++;
			   if(count>200){
				   Toast.makeText(mContext, "WIFI PC Linking test fail!!", Toast.LENGTH_SHORT).show();	
				   return;
			   }
		   }
			wifiManager.startScan();
			Toast.makeText(mContext, "WIFI PC Linking test success!!", Toast.LENGTH_SHORT).show();	
		}
	    else{
	    	wifiManager.setWifiEnabled(false);	
	    }		
	}
	
	/**
	 * 璁剧疆钃濈墮寮�鍏�/MS828
	 * @param status  0琛ㄧず鍏筹紝1琛ㄧず寮�
	 * @author wangst
	 * @Date 20150710
	 */
	public static void setBluetoothPower(int status){
		Log.d(TAG,"0712 setBluetoothPower");
		BluetoothAdapter mAdapter= BluetoothAdapter.getDefaultAdapter();
		if(null == mAdapter){
			Log.d(TAG,"setBluetoothPower BluetoothAdapter is null");
			return;
		}
		Log.d(TAG,"setBluetoothPower status = " + status);
		Log.d(TAG,"setBluetoothPower isEnable = " + mAdapter.isEnabled());
		if(1 == status){
			if(!mAdapter.isEnabled()){
				mAdapter.enable();
			}
		} else if(0 == status){
			if(mAdapter.isEnabled()){
				mAdapter.disable();
			}
		}
	}
	
	/*date:2014.01.16 
     * add by:yangms
     * Blutooth*/
	public static short[] getBluetoothvsync(){
		short i[]={0};
		int period=TVDefine.period;
		Log.v("luofg","period:"+TVDefine.period + "status_3d:"+ TVDefine.status_3d);
		float tmpVal;
		tmpVal = (float) 1000000.00 / period;
		int sync_freq = Math.round(tmpVal);
		Log.v("luofg", "sync_freq:"+sync_freq);
		
		if(period==-1&&TVDefine.status_3d==true)
		{
			i[0]=0;
			return i;
		}
		else if(TVDefine.status_3d==false)
		{
			i[0]=1;
			return i;
		}
		else if(sync_freq!=60){
			i[0]=0;
			return i;
		}else if(sync_freq==60){
			TVDefine.bluetoothstatus=true; //褰撴椤硅繍琛屾椂璁や负钃濈墮杩炴帴
			i[0]=2;
			return i;
		}
			
		return i;
	}
	
	/*date:2014.01.16 
     * add by:yangms
     * Blutooth*/
	public static short[] getBluetoothsync() {
		// TODO Auto-generated method stub
		short i[]={0};
		if(TVDefine.bluetoothstatus)
		{
			i[0]=1;
			return i;
		}else{
			i[0]=0;
			return i;
		}
		
	}
	public static short[] getWifiLeve() {
		short i[]={0};
	   
		WifiManager wifiManager = (WifiManager)mContext.getSystemService(mContext.WIFI_SERVICE);
		
		 if(!wifiManager.isWifiEnabled())
		    {
			 setWiFiPower(DEFS.COMMON_ON);
		    }
		List<ScanResult> mList= wifiManager.getScanResults();
		if(mList==null){
			i[0]=0;
			return i;
		}
		i[0]=5;
		ScanResult mScanResult =null;
		int y=1;
		for(y=1;y<mList.size();y++)
		{ 
			mScanResult = mList.get(y);
			Debug.v(TAG, "mScanResult.SSID=="+mScanResult.SSID); 
			if(mScanResult.SSID.equals("TCLIPTV"))
			{
			  	Debug.v(TAG, "TCL-WiFi=="+mScanResult.SSID);
			  	i[0]=(short) wifiManager.calculateSignalLevel(mScanResult.level, 5);
		        Debug.v(TAG, "TCL-WiFi leave=="+i); 
		        break;
			}
		}
		
		if(y==mList.size()) i[0]=0;
		
		return i;
	}
	
	public static boolean isWifiConnected(){
		if (WifiMultiSupport.WifiDeviceNum() < 1) {			
			return false;
		}else {
			return true;
		}
	}
	
	public static void setWifiLink()
	{
		if(isWifiConnected()){
			Utils.intentHandler(DEFS.Package_Android_Setting);			
//			setWiFiPower(DEFS.COMMON_ON);
		}else {
			Toast.makeText(mContext, "WIFI Device not connected!!", Toast.LENGTH_SHORT).show();
		}		
	}
	
	public static void setDBCActivity()
	{
		ThirdParty.setNatureLightEnabled(DEFS.Disable);
		ThirdParty.setGraphicBacklight(100);
		ThirdParty.sendMsgToDBC(0);

	}
	
	
	private static TMediaPlayer mVideoPlayer = null;
	private static int EnableKaraokeFlag = DEFS.COMMON_OFF;
	public static void EnableMic(int flag)
	{
		if((flag == DEFS.COMMON_ON) && (EnableKaraokeFlag == DEFS.COMMON_OFF))
		{
			if(ThirdParty.getSourceType().equalsIgnoreCase("STORAGE")||ThirdParty.getSourceType().equalsIgnoreCase("KTV")) {
				Toast.makeText(mContext, "Karaoke Enable!",Toast.LENGTH_SHORT).show();
//				if(mVideoPlayer == null) {
////					mVideoPlayer = (TMediaPlayer) TMediaPlayer.create(mContext, R.raw.video);
//					mVideoPlayer = new TMediaPlayer();
//					Debug.v(TAG, "[TMediaPlayer]new mVideoPlayer = "+mVideoPlayer);
////					InputStream fd = mContext.getResources().openRawResource(R.raw.video);
//					
//					AssetFileDescriptor fileDescriptor = null;
//					try 
//					{
//						fileDescriptor = mContext.getAssets().openFd("video");
//					    mVideoPlayer.setDataSource(fileDescriptor.getFileDescriptor(),fileDescriptor.getStartOffset(), fileDescriptor.getLength());
//						mVideoPlayer.setLooping(true); 
//						mVideoPlayer.prepare();   
//						mVideoPlayer.start();
//
//					} catch (IllegalArgumentException e) {
//						// TODO Auto-generated catch block
//						e.printStackTrace();
//					} catch (SecurityException e) {
//						// TODO Auto-generated catch block
//						e.printStackTrace();
//					} catch (IllegalStateException e) {
//						// TODO Auto-generated catch block
//						e.printStackTrace();
//					} catch (IOException e) {
//						// TODO Auto-generated catch block
//						e.printStackTrace();
//					} catch (Exception e) {
//						// TODO Auto-generated catch block
//						e.printStackTrace();
//					} finally {
//						if(fileDescriptor != null) {
//							try {
//								fileDescriptor.close();
//							} catch (IOException e) {
//								e.printStackTrace();
//							}
//						}
//					}
//				}
				ThirdParty.setMicphoneStatus(1);
				ThirdParty.setKaraOKBackgroundVolume((short) (30));
				ThirdParty.setKaraOKMicphoneVolume((short) (80));
				EnableKaraokeFlag = DEFS.COMMON_ON;
			}
		}
		else if((flag == DEFS.COMMON_OFF) && (EnableKaraokeFlag == DEFS.COMMON_ON))
		{

		}
	}
	public static void handlerAsyncCmdReset()
	{
		DEFS.asyncCommand = 0;
		DEFS.asyncCommandArg1 = 0;
		DEFS.asyncCommandArg2 = 0;
	}
	private static Handler handlerAsyncCmd= new Handler();
	private static Runnable handlerAsyncCmdTask = new Runnable() 
	{
		public void run()
		{
			int Command = DEFS.asyncCommand;
			int CommandArg1 = DEFS.asyncCommandArg1;
			int CommandArg2 = DEFS.asyncCommandArg2;
			
			switch(Command) {
			case DEFS.CMD_ChannelPreSet:
				handlerAsyncCmdReset();
				AsyncsetATVChannel(1);
//					TV.setSource(DEFS.SOURCE_DTV, 1);
//					Thread.currentThread().sleep(2000);
//					TV.setSource(DEFS.SOURCE_ATV, 1);
				break;
			case DEFS.CMD_setDTVChannel:
				handlerAsyncCmdReset();
				int dtvType = CommandArg1;
				int chNum = CommandArg2;
				
//				if(!ThirdParty.getSourceType().equalsIgnoreCase("DTV")) {
//					TV.setSource(DEFS.SOURCE_DTV, 1);
//					ThirdParty.setDtvType(dtvType);
//		    	}else{
//		    		if(ThirdParty.getDtvType() != dtvType){
//		    			ThirdParty.setDtvType(dtvType);
//		    		}else{
//		    			ThirdParty.SetDtvTypeAndSelectProgram(dtvType, chNum);
//		    		}
//		    	}
				ThirdParty.SetDtvTypeAndSelectProgram(dtvType, chNum);
				break;
				
//				//鏀惧埌setSource callback閲岄潰澶勭悊
//			case DEFS.CMD_setATVChannel:
//				break;
			case DEFS.CMD_EnableKaraoke:
				handlerAsyncCmdReset();
				if((CommandArg1 == DEFS.COMMON_ON)&&(EnableKaraokeFlag == DEFS.COMMON_OFF)) {
					if(ThirdParty.getSourceType().equalsIgnoreCase("STORAGE")) {
						DEFS.asyncCommand = DEFS.CMD_EnableKaraokePre;
						DEFS.asyncCommandArg1 = DEFS.COMMON_ON;
						TV.setSource(DEFS.SOURCE_KTV, 1);
					}
					else {
						DEFS.asyncCommand = DEFS.CMD_EnableKaraoke;
						TV.setSource(DEFS.SOURCE_STORAGE, 1);
					}
				}
				else if((CommandArg1 == DEFS.COMMON_OFF)&&(EnableKaraokeFlag == DEFS.COMMON_ON)) {
					Toast.makeText(mContext, "Karaoke Disable",Toast.LENGTH_SHORT).show();
					if (mVideoPlayer != null) {
						mVideoPlayer.stop();
						mVideoPlayer.reset();
						mVideoPlayer.release();
						mVideoPlayer = null;
						Debug.v(TAG, "[TMediaPlayer]release");
					}
					ThirdParty.setMicphoneStatus(0);
					//ThirdParty.SetDtvTypeAndSelectProgram(DEFS.TYPE_DVBC, 2);
					ThirdParty.setLastSourceType();
					EnTCLInputSource inputSource = ThirdParty.mTvCommonManager.getCurrentInputSource();
					int index = ThirdParty.mTvChannelManager.getCurrentChannelNumber();
					if(inputSource == EnTCLInputSource.EN_TCL_ATV )
					{
						ThirdParty.selectProgram(index);
					}
					else if(inputSource == EnTCLInputSource.EN_TCL_DTV)
					{
						ThirdParty.selectProgramDTV(index);
					}
					EnableKaraokeFlag = DEFS.COMMON_OFF;
				}

				break;
			}
			
		}
	};
	public static void AsyncPresetChannel() {
		DEFS.asyncCommand = DEFS.CMD_ChannelPreSet;
		handlerAsyncCmd.post(handlerAsyncCmdTask);
	}

	public static void AsyncsetDTVChannel(int arg1,int arg2) {
		DEFS.asyncCommand = DEFS.CMD_setDTVChannel;
		DEFS.asyncCommandArg1 = arg1;
		DEFS.asyncCommandArg2 = arg2;
		handlerAsyncCmd.post(handlerAsyncCmdTask);
	}
	
	public static void AsyncsetATVChannel(int arg1) {
		if(ThirdParty.getSourceType().equalsIgnoreCase("ATV")) {
			TV.setATVChannel(arg1);
		}
		else {
			DEFS.asyncCommand = DEFS.CMD_setATVChannel;
			DEFS.asyncCommandArg1 = arg1;
			TV.setSource(DEFS.SOURCE_ATV,1);
		}
	}
	
	public static void AsyncEnableKaraoke(int flag)
	{
		
		if(flag == DEFS.COMMON_ON) {
			DEFS.asyncCommand = DEFS.CMD_EnableKaraoke;
			DEFS.asyncCommandArg1 = flag;
			handlerAsyncCmd.post(handlerAsyncCmdTask);
		}
		else {
			DEFS.asyncCommand = DEFS.CMD_EnableKaraoke;
			DEFS.asyncCommandArg1 = flag;
			handlerAsyncCmd.post(handlerAsyncCmdTask);
		}
	}
	public static String LocalDimmingVersion() { 
		String version_str = ThirdParty.getLocalDimmingVersion(); 
		if (version_str != null) { 
			Toast.makeText(mContext, version_str, Toast.LENGTH_LONG).show(); 
			return version_str;
		} else { 
			Toast.makeText(mContext, "Local Dimming get version Fail", Toast.LENGTH_LONG).show(); 
			return "";
		} 
	} 

	public static void LocalDimmingUpgrade() {
		String path = getUSBMountPath(mContext);
		if(null==path || ("".equals(path)) ){
			Toast.makeText(mContext, "NO_USB_MOUNT", Toast.LENGTH_SHORT).show();
			return;
		} 
		else if (LDrunning == true)
		{
			Toast.makeText(mContext, "Updating", Toast.LENGTH_SHORT).show();
			return;			
		}
		else {
			new Thread(new Runnable() {
				@Override
				public void run() {
					Looper.prepare();
					LDrunning = true;
					boolean result = ThirdParty.LocalDimmingUpgrade();
					if (result) {
						Toast.makeText(mContext, "Local Dimming Upgrade OK",
								Toast.LENGTH_LONG).show();
					} else {
						Toast.makeText(mContext, "Local Dimming Upgrade Fail",
								Toast.LENGTH_LONG).show();
					}
					LDrunning = false;
					Looper.loop();
				}
			}).start();
		}
	}
	public static void ToastGammaTableCheckResult(int result) {
		if(result == 0) {
			Toast.makeText(mContext, "Gamma Table Check Fail",
					Toast.LENGTH_LONG).show();
		} else {
			Toast.makeText(mContext, "Gamma Table Check Success",
					Toast.LENGTH_LONG).show();
		}
	}
}
