package com.tcl.factory.utils;
 
import android.content.Context;
import android.content.Intent;
import android.view.Gravity;
import android.widget.Toast;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.io.InputStream;  

import com.tcl.factory.def.DEFS;
import com.tcl.factory.thirdparty.ThirdParty;

public class Utils {
	
	public static Context mContext;

	private final static String TAG = "utils";

public static void intentHandler(String packageName, String activityName)
{
	try{
		Intent mIntent = new Intent();
		mIntent.setClassName(packageName, activityName);
		mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		mContext.startActivity(mIntent);
	}
	catch(Exception e){
		Debug.v(TAG, "intentHandler fail!");
	}
}

public static void intentHandler(String packageName)
{
	boolean result = ThirdParty.checkPackage("com.android.tv.settings");
	Intent mIntent = new Intent();
	if(result)
	{
		Debug.v(TAG, "com.android.tv.settings.connectivity.NetworkActivity ");
		mIntent.setClassName("com.android.tv.settings",
				"com.android.tv.settings.connectivity.NetworkActivity");
		mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
	}
	else
	{
		Debug.v(TAG, "intentHandler:android.intent.action.WIFISETTING ");
		mIntent.setAction("android.intent.action.WIFISETTING");  
		mIntent.putExtra("FromApp", "wifidirect");
		mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
	}
	mContext.startActivity(mIntent);
}

public static void showSourceType(String str){
	
//	TVInfoToast mTVInfoToast=new  TVInfoToast(mContext);
//	mTVInfoToast.showRightTopInfo(str);
	toastRightTopInfo(str);
}

public static void toastRightTopInfo(String str)
{
	if(str==null)str="";
	
	Toast toast = Toast.makeText(mContext, str, Toast.LENGTH_SHORT);

	int x = DEFS.DESKTOP_WIDTH / 2 - 100;
	int y =-(DEFS.DESKTOP_HEIGHT / 2) + 240;
	toast.setGravity(Gravity.CENTER,x,y);
	toast.show();
}

public static short[] String2Short(String str) {
	char[] tmpStr = str.toCharArray();
	short[] tmpShort = new short[tmpStr.length];
	for (int i = 0; i < tmpStr.length; i++) {
		tmpShort[i] = (short) tmpStr[i];
	}
	return tmpShort;
}

public static String mac2String(short[] data)
{
	String  str="";
  for(int i =0 ;i<data.length;i++){
	  str=str+Short.toString(data[i]);
  }
  return str;
}


	public static byte[] short2Byte(short[] data)
	{
		
		byte[] dataT= new byte[data.length];
		for (int i = 0; i < dataT.length; i++) {
			dataT[i] = (byte) data[i];
		}
	 
		return dataT;
	}
	
	public static short[] byte2Short(byte[] data)
	{

		short[] dataT= new short[data.length];
		for (int i = 0; i < dataT.length; i++) {
			dataT[i] = (short) data[i];
		}
		
		return dataT;
	}
 
	public static String short2String(short[] data)
	{  
		String  str="";
	  for(int i =0 ;i<data.length;i++){
		  str=str+Short.toString(data[i]);
	  }
	  return str;
	}
	
	public static String short2StringHex(short[] data)
	{  
		String  str="";
	  for(int i =0 ;i<data.length;i++){
		  str=str+Short.toString(data[i]);
	  }
	  return str;
	}
	
	public static short[] boolean2Short(boolean status)
	{  
		short[] data = {1};
		if(status)  
		{
			data[0]=1;
 		}
		else
		{
			data[0]=0;
		}
		return data;
	}

	public static short[] int2Short(int data[], int length) 
	{
		short[] dataT = new short[length];
 		int intLength = length / 2;
		for (int i = 0; i < intLength; i++) {
			dataT[i * 2 + 1] = (short) ((data[i] >> 8) & 0xff);
			dataT[i * 2] = (short) (data[i] & 0xff);
		}
		for (int i = 0; i < length; i++)
			Debug.v("dataIntToShort", "data is " + dataT[i]);
		return dataT;
	}
 
	public static boolean int2Boolean(int intValue)
	{
		if(intValue == 1)
			return true;
		else
			return false;
	}
	
	public static int boolean2Int(boolean booleanValue)
	{
		if(booleanValue)
			return 1;
		else
			return 0;
	}
	
	 
	static final  long CRC_TABLE[]=
		{                
			0x0000,0x1021,0x2042,0x3063,0x4084,0x50A5,0x60C6,0x70E7,
			0x8108,0x9129,0xA14A,0xB16B,0xC18C,0xD1AD,0xE1CE,0xF1EF
		};
	
	public static long CRCCalculate(short pBuffer[],  int ucLength)
	{
		long uwCRC=0;// 16 bits
		int ucTemp=0; 
		uwCRC=0xFFFF;
		for(int i=0;i<ucLength;i++)
		{
			ucTemp=(int)(uwCRC>>0x0C);   
			ucTemp=ucTemp&0xFF; 

			uwCRC<<=4; 
			uwCRC=0xFFFF&uwCRC; 

			int s=ucTemp^(pBuffer[i]>>0x04);
			s=s&0x0f;

			uwCRC^=CRC_TABLE[s];  
			uwCRC=0xFFFF&uwCRC; 	    

			ucTemp=(int)(uwCRC>>0x0C);   
			ucTemp=ucTemp&0xFF; 

			uwCRC<<=4;	
			uwCRC=0xFFFF&uwCRC; 	

			int s1=ucTemp^(pBuffer[i]&0x0F);
			s1=s1&0x0f;

			uwCRC^=CRC_TABLE[s1];  
			uwCRC=0xFFFF&uwCRC; 
		}
 		return uwCRC;
	}
	
	public static int[] dataChangeForEEP(short data[]) 
	{
		int len = data.length;
		int[] intData = null;
		int intArrayLength = len / 2;
		if (len % 2 == 0) 
		{
			intData = new int[intArrayLength];
			for (int i = 0; i < intArrayLength; i++) 
			{
				intData[i] = ((data[i * 2 + 1] << 8) & 0xff00) + data[i * 2];
				Debug.v("dataChangeForEEPw", "data is A " + intData[i]);
			}
		}
		return intData;
	}
	
	public static boolean verifyCommandDataLength(int cmdType,int cmdLength)
	{
		switch(cmdType)
		{
		// 1byte data
		case 0x10:case 0x11:case 0x12:case 0x13:case 0x14:case 0x15:case 0x16:case 0x17:case 0x19:case 0x1c:
		case 0x22:case 0x23:case 0x24:case 0x25:case 0x26:case 0x27:case 0x29:case 0x2a:
		case 0x30:case 0x31:case 0x32:case 0x33:case 0x34:case 0x35:case 0x36:case 0x37:case 0x38:case 0x39:
		case 0x40:case 0x41:case 0x42:case 0x43:case 0x44:case 0x45:case 0x46:case 0x47:
		case 0x50:case 0x52:case 0x54:case 0x57:case 0x5c:case 0x5e:
		case 0x60:case 0x61:case 0x62:case 0x67:
		case 0x70:case 0x76:case 0x78:case 0x7a:case 0x7c:case 0x7d:case 0x7e:case 0x7f:
		case 0x80:case 0x82:case 0x84:case 0x87:case 0x8c:
		case 0x90:case 0x91:case 0x94:case 0x97:
		case 0xb0:case 0xb4:case 0xb6:case 0xb8:case 0xbe:
		case 0xc0:case 0xc1:case 0xc2:case 0xc3:case 0xc5:case 0xc7:case 0xc8:
		case 0xd0:case 0xd1:case 0xda:
		case 0xe5:case 0xe7:
			if(cmdLength == 1)
				return true;
			break;
			// 2 byte data
		case 0x1a:
		case 0x20:
		case 0x4b:
		case 0x4c:
		case 0x59:
			if(cmdLength == 2)
				return true;
			break;
			// 3 byte data
		case 0x21:
		case 0x28:
		case 0x48:
		case 0x49:
		case 0x5b:
		case 0x93:
		case 0xE2:
			if(cmdLength == 3)
				return true;
			break;
			// 4 byte data
		case 0x1b:
		case 0x1d:
			if(cmdLength == 4)
				return true;
			break;
			// 6 byte data
		case 0x4d:
			if(cmdLength == 6)
				return true;
			break;
			// 7 byte data
		case 0x56:
			if(cmdLength == 7)
				return true;
			break;
			// 8 byte data
		case 0x4a:
			if(cmdLength == 8)
				return true;
			break;
		case 0x71:
			if (cmdLength <=22) 
			{
				return true;
			}
			break;
			// HDCP data
		case 0x72://register code 2012 2 13
			if(cmdLength == 11)
				return true;
			break;
		case 0x86:
			if(cmdLength == 255)
				return true;
			break;
		case 0xb2:
			if(cmdLength == 40)
				return true;
			break;
		case 0xb3:
			if(cmdLength == 6)
				return true;
			break;	
		default:
			break;
		}
		Debug.v(TAG, "[verifyCommandDataLength]Failed:cmdType/cmdLength = "+cmdType+"/"+cmdLength);
		return false;
	}

	
	 
	public static short[] getData(short[]bufferData){   
		short buffer[]=null;
		int dataLength=bufferData.length-5;
		//debug  if the data length buffer is null; danger!!!!
		if(dataLength==0){
			buffer=new short[1];
			buffer[0]=0;
			return buffer;
		}
		
		buffer=new short[dataLength];
		for(int i=0;i<dataLength;i++)
		{
			buffer[i]=bufferData[3+i];
 		}	
		return buffer;
	}
	public static short[] getData(short[]bufferData, int offset){//hdcpkey
		short buffer[]=null;
		int dataLength=bufferData.length-(offset+2);//offset(head)+2(crc)
		//debug  if the data length buffer is null; danger!!!!
		if(dataLength==0){
			buffer=new short[1];
			buffer[0]=0;
			return buffer;
		}
		
		buffer=new short[dataLength];
		for(int i=0;i<dataLength;i++)
		{
			buffer[i]=bufferData[offset+i];
 		}	
		return buffer;
	}
	
	
	public static String  getSourceName(int type, int index){
		
		String str = "";
		switch (type) {
		case DEFS.SOURCE_ATV :
			str = "ATV";
			break;
		case DEFS.SOURCE_AV:
			str = "AV"+ index;
			break;
		case DEFS.SOURCE_YPBPR:
			str = "YPbPr" + index;
			break;
		case DEFS.SOURCE_VGA:
			str = "VGA" + index;
			break;
		case DEFS.SOURCE_HDMI:
			str = "HDMI" + index;
			break;
		case DEFS.SOURCE_DTV:
			str = "DTV";
			break;
		case DEFS.SOURCE_STORAGE:
			str = "USB";
			break;
		case DEFS.SOURCE_KTV:
			str = "KTV";
			break;
		}
		return str;
	}	
	
	public static void showATVInfo(int index) {
		StringBuffer displaystr = new StringBuffer("");
		displaystr.append("ATV");
		displaystr.append("\n");
		displaystr.append(" "+index);
		
//		TVInfoToast mTVInfoToast=new  TVInfoToast(mContext);
//		mTVInfoToast.showRightTopInfo(displaystr.toString());
		toastRightTopInfo(displaystr.toString());
	}

	public static void showDTVInfo(int index ) {
		StringBuffer displaystr = new StringBuffer("");
		displaystr.append("DTV");
		displaystr.append("\n");
		displaystr.append(" "+index);
		
//		TVInfoToast mTVInfoToast=new  TVInfoToast(mContext);
//		mTVInfoToast.showRightTopInfo(displaystr.toString());
		toastRightTopInfo(displaystr.toString());
	}
	
//	public static String Short2BinString(short[] b) 
//	{  
//		String hs = "";  
//		char stmp = '0';  
//		int len = b.length;  
//		for (int n = 0; n < len; n++) {
//			stmp = (char)b[n];
//			hs = hs + stmp; 
//		}
//		return hs; 
//	}
	public static short[] BinString2Short(String str) 
	{  
		char[] tmpStr = str.toCharArray();
		short[] tmpShort = new short[tmpStr.length];
		for (int i = 0; i < tmpStr.length; i++) {
			tmpShort[i] = (short) tmpStr[i];
		}
		return tmpShort;
	}
	
	public static String byte2hex(byte[] b) 
	{  
		String hs = "";  
		String stmp = "";  
		int len = b.length;  
		for (int n = 0; n < len; n++) {   
			stmp = Integer.toHexString(b[n] & 0xFF);   
			if (stmp.length() == 1)    
				hs = hs + "0" + stmp;   
			else    
				hs = hs + stmp;  
		}
		return hs; 
	}
	public static byte[] hex2byte(String str) 
	{  
		if (str == null) {   
			return null;  
		}  
		int len = str.length();  
		if ((len == 0) || (len % 2 == 1))   
			return null;  
		byte[] b = new byte[len / 2];  
		try {   
			for (int i = 0; i < len; i += 2) {    
				b[(i / 2)] = (byte) Integer.decode("0x" + str.substring(i, i + 2)).intValue();
			}   
			return b;  
		} catch (Exception e) {  
		}  
		return null; 
	}
	
	
//	int byte2hex(char* b,char* hex,int n) 
//	{  
//		int i=0;
//		for(i=0;i<n;i++) {
//			sprintf(&hex[i*2],"%02x",b[i]);
//		}
//		return n;
//	}
//	int hex2byte(char* b,char* hex,int n) 
//	{
//		int i=0;
//		char hsb=0,lsb=0;
//		for(i=0;i<n;i++) {
//			hsb=hex[i*2];
//			lsb=hex[i*2+1];
//			
//			if(hsb>='0' && hsb<='9')
//				hsb-='0';
//			else if(hsb>='a' && hsb<='z')
//				hsb=hsb-'a'+10;
//			else if(hsb>='A' && hsb<='Z')
//				hsb=hsb-'A'+10;
//			else;
//			
//			if(lsb>='0' && lsb<='9')
//				lsb-='0';
//			else if(lsb>='a' && lsb<='z')
//				lsb=lsb-'a'+10;
//			else if(lsb>='A' && lsb<='Z')
//				lsb=lsb-'A'+10;
//			else;
//			
//			b[i] = (hsb<<4)|lsb;
//		}
//		return n;
//	}

	private static byte[] getFileDigest(FileInputStream reader, long size) 
			throws IOException, NoSuchAlgorithmException
	{ 
		MessageDigest digester = MessageDigest.getInstance("MD5");
		byte[] bytes = new byte[8192];
		int byteCount;
		while ((byteCount = reader.read(bytes)) > 0) 
		{
			digester.update(bytes, 0, byteCount);
		}
		byte[] digest = digester.digest();
		digester = null;
		System.gc();
		return digest;
	}
	public static boolean md5Check_file(String orig, String dest)
	{
		if (orig == null || dest == null)
		{
			return false;
		}
		boolean result = false;
		FileInputStream reader1 = null;
		FileInputStream reader2 = null;
		try {
			File file1 = new File(orig);
			reader1 = new FileInputStream(file1);
			byte[] digest1 = getFileDigest(reader1, file1.length());
			File file2 = new File(dest);
			reader2 = new FileInputStream(file2);
			byte[] digest2 = getFileDigest(reader2, file2.length());
			if (!Arrays.equals(digest1, digest2))
			{
				result = true;
			}
		} catch (Exception e) {
			result = false;
			e.printStackTrace();
		}
		finally
		{
			if (reader1 != null)
			{
				try 
				{
					reader1.close();
				} catch (IOException e) 
				{
					e.printStackTrace();
				}
			}
			if (reader2 != null)
			{
				try 
				{
					reader2.close();
				} catch (IOException e) 
				{
					e.printStackTrace();
				}
			}
		}
		return result;
	}

	public static boolean md5check_key(String fileName,String MD5)
	{
		return MD5.equals(getFileMD5String(fileName))?true:false;
	}

	public static String getFileMD5String(String fileName) 
	{
		File file = new File(fileName);
		String md5 = null;
		try
		{
			if (!file.exists())
			{
			    	return null;
			}
			md5 =  getFileMD5String(file);
			Debug.d(TAG,"file md5 = " +md5);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		return md5;
	}

	public   static  String getFileMD5String(File file)  throws  IOException, NoSuchAlgorithmException
	{		 
		InputStream fis;  
		fis = new  FileInputStream(file);  
		byte [] buffer =  new   byte [ 1024 ];  
		int  numRead =  0 ;  
		MessageDigest digester = MessageDigest.getInstance("MD5");
		while  ((numRead = fis.read(buffer)) >  0 ) {  
			digester.update(buffer, 0 , numRead);  
		}  
		fis.close();  
		return  bufferToHex(digester.digest());  
	}  
  
	private static String bufferToHex(byte bytes[])
	{
		return bufferToHex(bytes, 0, bytes.length);
	}
	private static String bufferToHex(byte bytes[], int m, int n)
	{
		StringBuffer stringbuffer = new StringBuffer(2 * n);
		int k = m + n;
		for (int l = m; l < k; l++)
		{
			appendHexPair(bytes[l], stringbuffer);
		}
		return stringbuffer.toString();
	}
	private static void appendHexPair(byte bt, StringBuffer stringbuffer)
	{
		char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6',
			'7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
		char c0 = hexDigits[(bt & 0xf0) >> 4];
		char c1 = hexDigits[bt & 0xf];
		stringbuffer.append(c0);
		stringbuffer.append(c1);
	}	

	public static boolean writeTxtFile(String fileName, String message)
	{
		File file = null;
		try {
			file = new File(fileName);
			if (!file.exists()) {
				Debug.d(TAG , "createNewFile:"+fileName);	
				file.createNewFile();
				file.setReadable(true, false);
				file.setWritable(true, false);
			}
			String tmp_str =message  + "\r\n";
			FileOutputStream fout = new FileOutputStream(file,true);
			byte[] bytes = tmp_str.getBytes();
			fout.write(bytes);
			fout.close();
			return true;
		}
		catch (Exception e) {
		 e.printStackTrace();
		}
		return false;
	}

}
