package com.wasu.cs.module;

import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.text.TextUtils;

import com.wasu.module.log.WLog;

import java.util.List;

import cn.com.wasu.main.BuildConfig;
import cn.com.wasu.main.ChannelFlavor;

/**
 * 屏保模块
 *  Created by danxingxi on 2015/11/25.
 */
public class ScreenSaverModule{

	public final static String TAG = "ScreenSaverModule";
	private static ScreenSaverModule mInstance;
	
	private static Intent intent;
	private static Context mContext;
	
	private Handler mHandler01 = new Handler();
	
	/* 上一次User有动作的Time Stamp */
	private long lastUpdateTime;
	/* 计算User有几秒没有动作的 */
	private long timePeriod;
	
	/* 静止超过N秒将自动进入屏保 */
	private float mHoldStillTime = 60*5;
	/*标识当前是否进入了屏保*/
	private boolean isRunScreenSaver;
    
	/*线程唤醒自己的时间间隔*/
	private long intervalKeypadeSaver = 1000*60*2;
	private boolean isVideoPlaying = false;
	/**
	 * 初始化
	 * 
	 * @param c
	 */
	public void init(Context c) {
		mContext =c;
		intent = new Intent();
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setAction("com.wasu.screensaver");
		/* 初始取得User可触碰屏幕的时间 */
		lastUpdateTime = System.currentTimeMillis();
		/*启动屏幕线程*/
		mHandler01.postAtTime(mTask01, intervalKeypadeSaver);
	}

	/**
	 * 获取单例
	 * 
	 * @return
	 */
	public static ScreenSaverModule getInstance() {
		if (null == mInstance) {
			synchronized (ScreenSaverModule.class) {
				if (null == mInstance) {
					mInstance = new ScreenSaverModule();
				}
			}
		}
		return mInstance;
	}
	
	/* private的构造函数用于避免外界直接使用new来实例化对象 */
	private ScreenSaverModule(){
	}
	
	/**
	 * 计时线程
	 */
	private Runnable mTask01 = new Runnable() {
		
		@Override
		public void run() {
			/* 计算User静止不动作的时间间距 */
			/**当前的系统时间 - 上次触摸屏幕的时间 = 静止不动的时间**/
			timePeriod = System.currentTimeMillis() - lastUpdateTime;
			
			/*将静止时间毫秒换算成秒*/
			float timePeriodSecond = ((float) timePeriod / 1000);

			if(timePeriodSecond > mHoldStillTime && !isRunScreenSaver){
				showScreenSaver();
			}else {
//				updateUserActionTime();
			}
			/*反复调用自己进行检查*/
			mHandler01.postDelayed(mTask01, intervalKeypadeSaver);	
		}
	};
	
	/**
	 * 显示屏保
	 */
	private void showScreenSaver(){
		//乐视、明基渠道不执行显示屏保操作，直接刷新计时器
		if (BuildConfig.FLAVOR.equalsIgnoreCase(ChannelFlavor.LETV_MARKET)
				|| BuildConfig.FLAVOR.equals("BenQ")) {
			updateUserActionTime();
			return;
		}

		if(isVideoPlaying){
			/*如果有视频正在播放就刷新计时器不显示屏保*/
			updateUserActionTime();
		}else{
			if(isAppOnForeground() && isForeground()){  //判断是否在前台，第一个方法有的机型不支持
				mContext.startActivity(intent);
			}else{
				WLog.i(TAG ,"app不在前台");
			}
			/**不管有没有显示屏保都需要刷新计时器**/
			updateUserActionTime();
		}
	}

	/**
	 * 屏幕正在显示
	 */
	public void inScreenSaver(){
		isRunScreenSaver = true;
	}
	/**
	 * 退出屏保
	 */
	public void outScreenSaver(){
		isRunScreenSaver = false;
	}
	
	public void setVideoPlaying(boolean isPlaying){
		isVideoPlaying = isPlaying;
	}
	
	/**
	 * 取消线程
	 */
	public void clearTask(){
		mHandler01.removeCallbacks(mTask01);
	}
	
	/*用户有操作的时候不断重置静止时间和上次操作的时间*/
	public void updateUserActionTime() {
		long tmp = System.currentTimeMillis();
		timePeriod = tmp - lastUpdateTime;
		lastUpdateTime = tmp;
	}

	//在进程中去寻找当前APP的信息，判断是否在前台运行
	private boolean isAppOnForeground() {
		ActivityManager activityManager =(ActivityManager) mContext.getSystemService(
				Context.ACTIVITY_SERVICE);
		String packageName =mContext.getPackageName();
		List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
		if (appProcesses == null)
			return false;
		for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
			if (appProcess.processName.equals(packageName)
					&& appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
				return true;
			}
		}
		return false;
	}

	private boolean isForeground() {
		if (mContext != null) {
			ActivityManager am = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
			ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
			String currentPackageName = cn.getPackageName();
			if (!TextUtils.isEmpty(currentPackageName) && currentPackageName.equals(mContext.getPackageName())) {
				return true;
			}
			return false;
		}
		return false;
	}

}
