package cn.net.handsetlib.utils;

import android.content.Context;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.security.SecureRandom;
import java.util.regex.Pattern;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import Decoder.BASE64Decoder;
import Decoder.BASE64Encoder;
import cilico.tools.barcode.Scanner;

/**
 * 
 * 对设备ID进行读取
 * 
 */
public class ReadDeviceIDUtil {
	private final static String DES = "DES";// DES模式加密
	private final static String DES_KYE = "jymfcpzs";// DES密钥
	/**
	 * "/CpzsHandset/"
	 */
	public final static String CpzsHandset = "/CpzsHandset/";//
	/**
	 * CpzsHandset+"config/"
	 */
	public final static String configFileName = CpzsHandset + "config";// 配置文件文件夹名字
	private final static String fileName = configFileName; // "/CpzsHandset/config";//
															// 文件夹名字
	private final static String CONFIG = "/DeviceId.config";// 配置名字
	private static final String TAG = "cpzsHandset";

	public static boolean WriteCofig(Context context, String stringToWrite) {
		boolean result = false;
		if (Environment.MEDIA_MOUNTED.equals(Environment
				.getExternalStorageState())) {
			String folderName = Environment.getExternalStorageDirectory()
					.getPath() + fileName;
			File folder = new File(folderName);
			if (folder == null || !folder.exists()) {
				folder.mkdirs();
			}
			File targetFile = new File(folderName + CONFIG);
			if (targetFile.exists()) {
				targetFile.delete();
			}
			OutputStreamWriter osw;

			try {
				if (!targetFile.exists()) {
					targetFile.createNewFile();

					osw = new OutputStreamWriter(new FileOutputStream(
							targetFile), "utf-8");
					osw.write(stringToWrite);
					osw.close();
				} else {
					osw = new OutputStreamWriter(new FileOutputStream(
							targetFile), "utf-8");
					osw.write("\n" + stringToWrite);
					osw.flush();
					osw.close();
				}
				result = true;
			} catch (Exception e) {
				Toast.makeText(context, e.toString(), Toast.LENGTH_LONG).show();
				result = false;
			}

		} else {
			// Toast.makeText(context, "未发现SD卡！", Toast.LENGTH_LONG).show();
			result = false;
		}
		return result;
	}

	/**
	 * 进行扫描的解密 2014-6-17下午4:10:55
	 * 
	 * @param data
	 * @return
	 */
	public static String readScanDecrypt(String data) {
		try {
			String ss = decrypt(data, DES_KYE);
			return ss;
		} catch (IOException e) {
			e.printStackTrace();
			return "设备id异常";
		} catch (Exception e) {
			e.printStackTrace();
			return "设备id异常";
		}
	}

	/**
	 * 读取sd卡中的配置文件 2014-6-10下午1:38:56
	 * 
	 * @param context
	 * @return
	 */
	public static String readSdcardConfig(Context context) {
		if (Environment.MEDIA_MOUNTED.equals(Environment
				.getExternalStorageState())) {

			String folderName = Environment.getExternalStorageDirectory()
					.getPath() + fileName;
			File folder = new File(folderName);
			if (folder == null || !folder.exists()) {
				folder.mkdirs();
			}
			File targetFile = new File(folder + CONFIG);
			String readStr = "";
			try {
				if (!targetFile.exists()) {
					targetFile.createNewFile();
					return "No Id";
				} else {
					InputStream in = new BufferedInputStream(
							new FileInputStream(targetFile));
					BufferedReader br = new BufferedReader(
							new InputStreamReader(in, "utf-8"));
					String tmp;
					while ((tmp = br.readLine()) != null) {
						readStr += decrypt(tmp, DES_KYE);
					}
					br.close();
					in.close();
					return readStr;
				}
			} catch (Exception e) {
				// Toast.makeText(context, e.toString(),
				// Toast.LENGTH_LONG).show();
				Log.i(TAG, "readSdcardConfig:" + e.toString());
				return "No Id";
			}
		} else {
			// Toast.makeText(context, "未发现SD卡！", Toast.LENGTH_LONG).show();
			return "SD Card error";
		}
	}

	// public static void main(String[] args) throws Exception {
	// String data = "123 456";
	// String key = "wang!@#$%";
	// System.err.println(encrypt(data, key));
	// System.err.println(decrypt(encrypt(data, key), key));
	//
	// }

	/**
	 * Description 根据键值进行加密
	 * 
	 * @param data
	 * @param key
	 *            加密键byte数组
	 * @return
	 * @throws Exception
	 */
	private static String encrypt(String data, String key) throws Exception {
		byte[] bt = encrypt(data.getBytes(), key.getBytes());
		String strs = new BASE64Encoder().encode(bt);
		return strs;
	}

	/**
	 * Description 根据键值进行解密
	 * 
	 * @param data
	 * @param key
	 *            加密键byte数组
	 * @return
	 * @throws IOException
	 * @throws Exception
	 */
	private static String decrypt(String data, String key) throws IOException,
			Exception {
		if (data == null)
			return null;

		BASE64Decoder decoder = new BASE64Decoder();
		byte[] buf = decoder.decodeBuffer(data);
		byte[] bt = decrypt(buf, key.getBytes());
		return new String(bt);
	}

	/**
	 * Description 根据键值进行加密
	 * 
	 * @param data
	 * @param key
	 *            加密键byte数组
	 * @return
	 * @throws Exception
	 */
	private static byte[] encrypt(byte[] data, byte[] key) throws Exception {
		// 生成一个可信任的随机数源
		SecureRandom sr = new SecureRandom();

		// 从原始密钥数据创建DESKeySpec对象
		DESKeySpec dks = new DESKeySpec(key);

		// 创建一个密钥工厂，然后用它把DESKeySpec转换成SecretKey对象
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
		SecretKey securekey = keyFactory.generateSecret(dks);

		// Cipher对象实际完成加密操作
		Cipher cipher = Cipher.getInstance(DES);

		// 用密钥初始化Cipher对象
		cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);

		return cipher.doFinal(data);
	}

	/**
	 * Description 根据键值进行解密
	 * 
	 * @param data
	 * @param key
	 *            加密键byte数组
	 * @return
	 * @throws Exception
	 */
	private static byte[] decrypt(byte[] data, byte[] key) throws Exception {
		// 生成一个可信任的随机数源
		SecureRandom sr = new SecureRandom();

		// 从原始密钥数据创建DESKeySpec对象
		DESKeySpec dks = new DESKeySpec(key);

		// 创建一个密钥工厂，然后用它把DESKeySpec转换成SecretKey对象
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
		SecretKey securekey = keyFactory.generateSecret(dks);

		// Cipher对象实际完成解密操作
		Cipher cipher = Cipher.getInstance(DES);

		// 用密钥初始化Cipher对象
		cipher.init(Cipher.DECRYPT_MODE, securekey, sr);

		return cipher.doFinal(data);
	}

	/**
	 * 获取id
	 * 
	 * @param context
	 * @return 2014-10-22下午2:25:13
	 */
	public static long getDevicId(Context context) {
		try {
			String deviceId = readSdcardConfig(context);
			long id = 0L;
			if (isNumber(deviceId)) {
				id = Long.valueOf(deviceId);
			} else if (deviceId.contains(Scanner.splitStr)) {
				id = Long.valueOf(deviceId.split(Scanner.splitStr)[0]);
			}
			return id;// 1000000000225L;
		} catch (Exception e) {
			return 0L;
		}
	}

	/**
	 * 判断是不是数字 2014-5-28下午1:56:22
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isNumber(String str) {
		return Pattern.compile("^\\d*$").matcher(str).matches();
	}

}
