package cn.com.wasu.main;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.util.Log;
import android.view.WindowManager;

import com.wasu.cs.model.BkbmTimeModel;
import com.wasu.statistics.PlayInfo;

import org.apache.http.conn.util.InetAddressUtils;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class AppUtil {
	private static List<OnNetStateListener> onNetStateListenerList = new ArrayList<OnNetStateListener>();
	public static final int ETHERNET_CONNECTED = 0;
	public final static int ETHERNET_DISCONNECTED = 1;
	public static final int WIFI_CONNECTED = 2;
	public final static int WIFI_DISCONNECTED = 3;
	private static int connType = WIFI_DISCONNECTED;
	public static int MAIN_PAGERVIEW_POSITION = 0;
	public static PlayInfo playInfo=new PlayInfo();
	private static int ID_OFFSET = 0x100;
	public static String playEnter="";//保存点播路径的入口
	/**边看边买配置文件**/

	//乐视渠道关闭边看边买
	public static boolean bkbmSwitch = ChannelFlavor.isLETV_MARKET() ? false : true; // 边看边买统一开关

	public static long watchTime = 0; // 观看间_边看边买
	public static List<BkbmTimeModel> bkbmTime;

//	public static List<AdBreak> bkbmBreak; // 边看边买数组
//	public static SparseIntArray bkbmTime; // 边看边买时间数组
//	public static List<Integer> bkbmTime; // 边看边买时间数组
	//	public static int bkbmIndex = 0;
//	public static int bkbmTotal = 7200; // 边看边买的总时长（s）
//	public static int bkbmInterval = 1440; // 边看边买间隔时长（s）
	public static String[] bkbmIgnore = {"新闻","中国蓝TV","求索","沙发院线","飞狐娱乐视频","少儿","军事"}; //不允许播放广告的ppv

	public static final String Home_Vip_Layout = "Home_Vip";
	public static final String Home_Rec_Layout = "Home_Rec";
	public static final String Home_Demand_Layout = "Home_Demand";
	public static final String Home_Life_Layout = "Home_Life";


	public static boolean isLimited() {
		boolean res = false;

		if (Runtime.getRuntime().availableProcessors() < 2) {
			res = true;
		}

		return res;
	}
	
	// 获取总运存大小
	public static long getTotalMemory(Context context) {
		String str1 = "/proc/meminfo";// 系统内存信息文件
		String str2;
		String[] arrayOfString;
		long initial_memory = 0;
		try {
			FileReader localFileReader = new FileReader(str1);
			BufferedReader localBufferedReader = new BufferedReader(localFileReader, 8192);
			str2 = localBufferedReader.readLine();// 读取meminfo第一行，系统总内存大小
			arrayOfString = str2.split("\\s+");
			initial_memory = Integer.valueOf(arrayOfString[1]).intValue() * 1024;// 获得系统总内存，单位是KB，乘以1024转换为Byte
			localBufferedReader.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		// Byte转换为KB或者MB，内存大小规格化
		return initial_memory / (1024 * 1024);
	}

	/**
	 * 获取进程name
	 * @param cxt
	 * @param pid
	 * @return
	 */
	public static String getProcessName(Context cxt, int pid) {
		ActivityManager am = (ActivityManager) cxt.getSystemService(Context.ACTIVITY_SERVICE);
		List<ActivityManager.RunningAppProcessInfo> runningApps = am.getRunningAppProcesses();
		if (runningApps == null) {
			return null;
		}
		for (ActivityManager.RunningAppProcessInfo procInfo : runningApps) {
			if (procInfo.pid == pid) {
				return procInfo.processName;
			}
		}
		return null;
	}
	
	public static void addOnNetStateListener(OnNetStateListener onsl) {
		if(onsl != null && !onNetStateListenerList.contains(onsl)) {
			onNetStateListenerList.add(onsl);
		}
	}
	
	public static void removeOnNetStateListener(OnNetStateListener onsl) {
		if(onsl != null) {
			onNetStateListenerList.remove(onsl);
		}
	}
	
	public static void updateNetConn(Context context) {
		
		connType = getNetConnStatus(context);
        
        for(OnNetStateListener nsl: onNetStateListenerList) {
        	if(nsl != null) {
        		nsl.onStateChanged(connType);
        	}
        }
	}
	
	@SuppressLint("InlinedApi") 
	public static int getNetConnStatus(Context context) {
		ConnectivityManager connectivityManager=(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo wifiNetInfo=connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        int status = WIFI_DISCONNECTED;
        
        if(wifiNetInfo != null && wifiNetInfo.isAvailable() && wifiNetInfo.isConnected()) {
        	status = WIFI_CONNECTED;
        } else {
        	NetworkInfo networkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_ETHERNET);
        	if(networkInfo != null && networkInfo.isAvailable() && networkInfo.isConnected()) {
        		status = ETHERNET_CONNECTED;
            }
        }
        
        return status;
	}
	
	public interface OnNetStateListener {
		public void onStateChanged(int state);
	}
	
	public static int createId() {
		return ID_OFFSET++;
	}
	
	public static Bitmap getBitmap(String path) throws IOException {
		URL url = new URL(path);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setConnectTimeout(5000);
		conn.setRequestMethod("GET");
		if(conn.getResponseCode() == 200) {
			InputStream inputStream = conn.getInputStream();
			Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
			return bitmap;
	    }
		
		return null;
	}
	
	public static Drawable loadImageFromNetwork(String url) {
		Drawable drawable = null;
		
		try{
			drawable = Drawable.createFromStream(new URL(url).openStream(), "image.jpg");
		} catch(IOException e) {
			e.printStackTrace();
		}
		
		return drawable;
	}
	
	public static float Default_H = 720.0f;
	
	@SuppressLint("NewApi")
	public static Point getScreenSize(Context context) {
		WindowManager windowManager = (WindowManager) context
				.getSystemService(Context.WINDOW_SERVICE);
		Point outSize = new Point();
		windowManager.getDefaultDisplay().getSize(outSize);
		return outSize;
	}
	
	public static float getAdapterHeight(Context context, int height) {
		float res = height;
		Point size = getScreenSize(context);
		
		res = height * size.y / Default_H;

		return res;
	}
	
	public static int getProRataH(Context context, int height) {
		return (int) getAdapterHeight(context, height);
	}

	/**
	 * 区分网络情况获取Ip地址
	 */
	public static String getIpAddress(Context context) {
		int status = getNetConnStatus(context);
		if(status == ETHERNET_CONNECTED ){
			return getWXLocalIpAddress(context);
		}else if (status == WIFI_CONNECTED){
			return getWifiLocalIpAddress(context);
		}else {
			return "10.99.115.159";
		}
	}

	/**
	 * 获取有网线下的Ip地址
	 * 需要添加权限:<uses-permission android:name="android.permission.INTERNET" />
	 *
	 * @param context 上下文
	 * @return IP地址
	 */
	private static String getWXLocalIpAddress(Context context) {
		String ipv4 = "0.0.0.0";
		try {
			List<NetworkInterface> nilist = Collections.list(NetworkInterface
					.getNetworkInterfaces());
			for (NetworkInterface ni : nilist) {
				List<InetAddress> ialist = Collections.list(ni
						.getInetAddresses());
				for (InetAddress address : ialist) {
					if (!address.isLoopbackAddress()
							&& InetAddressUtils.isIPv4Address(ipv4 = address
							.getHostAddress())) {
						return ipv4;
					}
				}
			}

		} catch (SocketException ex) {
			Log.e("AppUtil", ex.toString());
		}
		return "10.99.115.159";
	}

	/**
	 * 获取Wifi下的Ip地址
	 * 需要添加权限: <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
	 *
	 * @param context 上下文
	 * @return IP地址
	 */
	private static String getWifiLocalIpAddress(Context context) {
		WifiManager wifi = (WifiManager) context
				.getSystemService(Context.WIFI_SERVICE);
		WifiInfo info = wifi.getConnectionInfo();
		int ipAddress = info.getIpAddress();
		if (ipAddress != 0) {
			return intToIp(ipAddress);
		} else {
			return "10.99.115.159";
		}
	}

	private static String intToIp(int i) {
		return (i & 0xFF) + "." + ((i >> 8) & 0xFF) + "." + ((i >> 16) & 0xFF)
				+ "." + ((i >> 24) & 0xFF);
	}
}
