package com.tcl.customerapi;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;

import android.app.ActivityManager;
import android.app.Instrumentation;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.hardware.input.InputManager;
import android.os.SystemClock;
import android.util.Log;
import android.view.InputDevice;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;

public class LauncherHelper {
    private Context mContext;
    private String[] launcherList;
    private String[] launcherPkgNameList;
    private int curLauncher;
    private List<ResolveInfo> infors;
    private ComponentName[] components;
//	private String TAG_LAUNCHER = "persist.sys.default_launcher";

    private String TAG = LauncherHelper.class.getName();

    public LauncherHelper(Context context) {
        mContext = context;

        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);
        PackageManager pm = context.getPackageManager();
        infors = pm.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
        int size = infors.size();
        launcherList = new String[size];
        launcherPkgNameList = new String[size];
        components = new ComponentName[size];
        for (int i = 0; i < size; i++) {
            ResolveInfo info = infors.get(i);
            launcherList[i] = (String) info.loadLabel(pm);
            components[i] = new ComponentName(info.activityInfo.packageName,
                    info.activityInfo.name);
            launcherPkgNameList[i] = info.activityInfo.packageName;
            Log.i(TAG, "launcherPkgNameList[" + i + "]:" + launcherPkgNameList[i]);
        }
        curLauncher = getCurLauncherIndex();

    }

    public int getCurLauncherIndex() {
        final Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);
        PackageManager pm = mContext.getPackageManager();
        final ResolveInfo res = pm.resolveActivity(intent, 0);
        if (res == null) {
            return 0;
        }
        if (res.activityInfo == null) {
            // should not happen. A home is always installed, isn't it?
            return 0;
        }
        if (res.activityInfo.packageName.equals("android")) {
            // 有多个桌面程序存在，且未指定默认项时；     
            return 0;
        } else {
            Log.d(TAG, "res = " + res);
//        	SettingLog.logI(TAG, "infors.indexOf(res):" + infors.indexOf(res));
            String tmp = (String) res.loadLabel(pm);
            Log.i(TAG, "tmp:" + tmp);
            for (int i = 0; i < launcherList.length; i++) {
                if (launcherList[i].equals(tmp)) {
                    return i;
                }
            }
            return 0;
        }
    }


    public String[] getLaunchersList() {
        Log.v(TAG, "getLaunchersList");
        return launcherList;
    }

    public void setLauncher(int launcher) {
        Log.d(TAG, "setLauncher launcher:" + launcher);
        if (launcher == curLauncher) {
            return;
        }

        PackageManager pm = mContext.getPackageManager();
        ComponentName comp = new ComponentName(infors.get(launcher).activityInfo.packageName,
                infors.get(launcher).activityInfo.name);
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.intent.action.MAIN");
        filter.addCategory("android.intent.category.HOME");
        filter.addCategory("android.intent.category.DEFAULT");

        pm.clearPackagePreferredActivities(infors.get(curLauncher).activityInfo.packageName);
        pm.addPreferredActivity(filter, IntentFilter.MATCH_CATEGORY_EMPTY, components, comp);
        int inputSource = InputDevice.SOURCE_KEYBOARD;
        sendKeyEvent(inputSource, KeyEvent.KEYCODE_HOME);//注入Home事件，立即切换Launcher
        killLauncher();
        curLauncher = launcher;

    }

    /**
     * 切换Launcher之后，kill 之前的launcher应用
     */
    private void killLauncher() {
        String pkgName = "";
        if (launcherPkgNameList != null && launcherPkgNameList.length > 0) {
            pkgName = launcherPkgNameList[curLauncher];
        }
        ActivityManager am = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
        try {
            Method forceStopPackage;
            forceStopPackage = am.getClass().getDeclaredMethod("forceStopPackage", String.class);
            forceStopPackage.setAccessible(true);
            try {
                forceStopPackage.invoke(am, pkgName);
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
            Log.i(TAG, "kill progress end:");
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }

    public int getCurLauncher() {
        Log.d(TAG, "getCurLauncher curLauncher = " + curLauncher);
        return curLauncher;
    }

    private void sendKeyEvent(int inputSource, int keyCode) {
        long now = SystemClock.uptimeMillis();
        injectKeyEvent(new KeyEvent(now, now, KeyEvent.ACTION_DOWN, keyCode, 0, 0,
                KeyCharacterMap.VIRTUAL_KEYBOARD, 0, 0, inputSource));

        injectKeyEvent(new KeyEvent(now, now, KeyEvent.ACTION_UP, keyCode, 0, 0,
                KeyCharacterMap.VIRTUAL_KEYBOARD, 0, 0, inputSource));
    }

    private void injectKeyEvent(KeyEvent event) {
        Log.i(TAG, "injectKeyEvent: " + event);
//        InputManager.getInstance().injectInputEvent(event,
////                InputManager.INJECT_INPUT_EVENT_MODE_WAIT_FOR_FINISH);
        sendKey(event.getKeyCode());
    }

    public boolean sendKey(int keycode) {
        try {
            Instrumentation inst = new Instrumentation();
            inst.sendKeyDownUpSync(keycode);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public int getUserLauncherId(String packageName) {

        if (infors != null && infors.size() != 0) {

            for (int i = 0; i < infors.size(); i++) {

                if (infors.get(i).activityInfo.packageName.equals(packageName)) {

                    return i;
                }
            }
        }
        return -1;
    }

}
