package com.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.lang.reflect.Method;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.drawable.GradientDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Environment;

public class SysUtil {

	private static String mac = "";

	/* 把数字转换成颜色 */
	public static int toHex(String value) {
		int color = (int) Long.parseLong("ff" + Integer.toHexString(Integer.parseInt(value)), 16);
		if (color == 4080)
			color = Color.BLACK;
		return color;
	}

	/* 把6位颜色直(0xff0000) 转换成颜色 */
	public static int toColor(int color) {
		int red = (color & 0xff0000) >> 16;
		int green = (color & 0x00ff00) >> 8;
		int blue = (color & 0x0000ff);
		return Color.rgb(red, green, blue);
	}

	public static GradientDrawable GradientDrawable(String color) {
		GradientDrawable gd = new GradientDrawable();
		gd.setCornerRadius(3);
		gd.setColor(toHex(color));// 设置颜色
		// gd.setStroke(3, toHex("14079443"));
		return gd;
	}

	public static GradientDrawable GradientDrawable(int color) {
		GradientDrawable gd = new GradientDrawable();
		gd.setCornerRadius(3);
		gd.setColor(color);// 设置颜色
		// gd.setStroke(3, toHex("14079443"));
		return gd;
	}

	public static GradientDrawable GradientDrawable() {
		GradientDrawable gd = new GradientDrawable();
		gd.setCornerRadius(3);
		gd.setColor(Color.WHITE);// 设置颜色
		// gd.setStroke(3, toHex("14079443"));
		return gd;
	}

	public static boolean isTopApp(Context context) {
		ActivityManager activityManager = (ActivityManager) context.getSystemService(context.ACTIVITY_SERVICE);
		List<RunningTaskInfo> tasks = activityManager.getRunningTasks(1);
		if (tasks == null || tasks.isEmpty()) {
			return false;
		}
		RunningTaskInfo task = tasks.get(0);
		String className = task.topActivity.getClassName();
		System.out.println(className + "-----------------------------");
		return className.equals(((Activity) context).getComponentName().getClassName());
	}

	// public static String getMac() {
	// String macSerial = null;
	// String str = "";
	// try {
	// Process pp = Runtime.getRuntime().exec(
	// "cat /sys/class/net/wlan0/address ");
	// InputStreamReader ir = new InputStreamReader(pp.getInputStream());
	// LineNumberReader input = new LineNumberReader(ir);
	//
	// for (; null != str;) {
	// str = input.readLine();
	// if (str != null) {
	// macSerial = str.trim();// 去空格
	// break;
	// }
	// }
	// } catch (IOException ex) {
	// // 赋予默认值
	// ex.printStackTrace();
	// }
	// return macSerial;
	//
	// }
	public static boolean isNetworkConnected(Context context) {
		if (context != null) {
			ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
			if (mNetworkInfo != null) {
				return mNetworkInfo.isAvailable();
			}
		}
		return false;
	}

/*	   *//**
     * 获取移动设备本地IP
     *
     * @return
     *//*
    private static InetAddress getLocalInetAddress() {
        InetAddress ip = null;
        try {
            // 列举
            Enumeration<NetworkInterface> en_netInterface = NetworkInterface
                    .getNetworkInterfaces();
            while (en_netInterface.hasMoreElements()) {// 是否还有元素
                NetworkInterface ni = (NetworkInterface) en_netInterface
                        .nextElement();// 得到下一个元素
                Enumeration<InetAddress> en_ip = ni.getInetAddresses();// 得到一个ip地址的列举
                while (en_ip.hasMoreElements()) {
                    ip = en_ip.nextElement();
                    if (!ip.isLoopbackAddress()
                            && ip.getHostAddress().indexOf(":") == -1)
                        break;
                    else
                        ip = null;
                }

                if (ip != null) {
                    break;
                }
            }
        } catch (SocketException e) {

            e.printStackTrace();
        }
        return ip;
    }*/
	public static String getLocalMacAddress(Activity activity) {
		WifiManager wifi = (WifiManager) activity.getSystemService(Context.WIFI_SERVICE);
		WifiInfo info = wifi.getConnectionInfo();
		mac = info.getMacAddress();
		
		if (mac == null || mac.length() < 1 || mac.startsWith("02:00:00:00:00:"))
			mac = getMacAddress();
		
		mac = mac.toUpperCase();
		
		return mac;
	}

	@SuppressLint("NewApi")
	public static String getMacAddress() {
		/*
		 * 获取mac地址有一点需要注意的就是android
		 * 6.0版本后，以下注释方法不再适用，不管任何手机都会返回"02:00:00:00:00:00"
		 * 这个默认的mac地址，这是googel官方为了加强权限管理而禁用了getSYstemService
		 * (Context.WIFI_SERVICE)方法来获得mac地址。
		 */
		// String macAddress= "";
		// WifiManager wifiManager = (WifiManager)
		// MyApp.getContext().getSystemService(Context.WIFI_SERVICE);
		// WifiInfo wifiInfo = wifiManager.getConnectionInfo();
		// macAddress = wifiInfo.getMacAddress();
		// return macAddress;

		String macAddress = null;
		StringBuffer buf = new StringBuffer();
		NetworkInterface networkInterface = null;
		try {
			networkInterface = NetworkInterface.getByName("eth1");
			if (networkInterface == null) {
				networkInterface = NetworkInterface.getByName("wlan0");
			}
			if (networkInterface == null) {
				return "02:00:00:00:00:02";
			}
			byte[] addr = networkInterface.getHardwareAddress();
			for (byte b : addr) {
				buf.append(String.format("%02X:", b));
			}
			if (buf.length() > 0) {
				buf.deleteCharAt(buf.length() - 1);
			}
			macAddress = buf.toString();
		} catch (SocketException e) {
			e.printStackTrace();
			return "02:00:00:00:00:02";
		}
		return macAddress;
	}

	public static String mapFirst(List list) {
		String filedName = null;
		Set<String> set = ((HashMap) list.get(0)).keySet();
		for (String s : set) {
			filedName = s;
			break;
		}
		return filedName;
	}

	@SuppressLint({ "NewApi", "NewApi" })
	public static String getSerialNum() {
		// String serialNum = null;
		// try {
		// Class<?> classZ = Class.forName("android.os.SystemProperties");
		// Method get = classZ.getMethod("get", String.class);
		// serialNum = (String) get.invoke(classZ, "ro.serialno");
		// } catch (Exception e) {
		// }
		String serialNum = android.os.Build.SERIAL;
		return serialNum;
	}

	/* 东集pda专用获取SN */
	public static String getSn() {
		//return mac.toLowerCase().replace(":", "");
		
		String sn = getSn0("data/data/sn");
		if (sn == null || sn.trim().length() < 1)
			sn = getSn1();
		if (sn.length() >= 15) {
			sn = getSn0("/sys/class/net/wlan0/address");
			sn = sn.replace(":", "");
		}

		if (sn != null && sn.trim().length() > 0)
			return sn;
		else
			return mac.toLowerCase().replace(":", "");
	}

	public static String getSn0(String fileName) {
		String SN_FILE = fileName;
		InputStreamReader isr = null;
		FileInputStream inputStream = null;
		byte[] buffer = new byte[64];
		File file = new File(SN_FILE);
		int code = 0;
		try {
			inputStream = new FileInputStream(file);
			inputStream.read(buffer, 0, buffer.length);

			String str = new String(buffer).toString();

			return str.trim().length() > 0 ? str.trim() : "";
		} catch (IOException e) {
			return "";
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	public static String getSn1() {
		try {
			Method systemProperties_get = Class.forName("android.os.SystemProperties").getMethod("get", String.class);
			// String []propertys = {"ro.boot.serialno", "ro.serialno"};
			String rtn = (String) systemProperties_get.invoke(null, "ro.boot.serialno");
			if (rtn == null || rtn.trim().length() < 1)
				rtn = (String) systemProperties_get.invoke(null, "ro.serialno");
			return rtn == null ? "" : rtn;
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}

	}

	/*
	 * 检查存储卡是否插入
	 * 
	 * @return
	 */
	public static boolean isHasSdcard() {
		String status = Environment.getExternalStorageState();
		if (status.equals(Environment.MEDIA_MOUNTED)) {
			return true;
		} else {
			return false;
		}
	}

	/*
	 * 拍照图片文件名
	 */
	private static String getPhotoFileName() {
		Date date = new Date(System.currentTimeMillis());
		SimpleDateFormat dateFormat = new SimpleDateFormat("'IMG'_yyyyMMdd_HHmmss");
		return dateFormat.format(date) + ".jpg";
	}

	public static byte[] bitmapToByte(Bitmap bitmap) {
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		bitmap.compress(CompressFormat.JPEG, 60, output);
		byte[] result = output.toByteArray();
		try {
			output.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}
}
