package com.tcl.ah.tvcontrol.api;

import android.app.ActivityManager;
import android.app.Instrumentation;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.util.Log;

import com.tcl.ah.tvcontrol.Constants;
import com.tcl.ah.tvcontrol.MyApplication;
import com.tcl.snack.os.SystemProperties;
import com.tcl.tvmanager.TTvFunctionManager;

import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;


public class KeyEventHelper {

    private final static String TAG = "KeyEventHelper";

    final static String ACTION_POWER_STATE = "set_powerstate"; //电源
    final static String ACTION_DIRECTION = "set_direction";       //上下左右
    final static String ACTION_VOLUME = "set_volume";             //音量
    final static String ACTION_CHANNEL = "set_channel";           //频道
    final static String ACTION_HOMEPAGE = "set_homepage";         //主页
    final static String ACTION_BACKTRACK = "set_backtrack";       //返回
    final static String ACTION_SYS_UPGRADE = "set_wififw";        //系统升级

    private static final String PACKAGE_HOME = "com.tcl.cyberui";
    public static final String PACKAGE_HOME_ACTIVITY = "com.tcl.cyberui.MainActivity";
    public static final String PERSIST_POWER_STATUS = "persist.sys.curpowerstatus";

    public static final int KEYCODE_CHANNEL_UP = 166;
    public static final int KEYCODE_CHANNEL_DOWN = 167;
    public static final int KEYCODE_DPAD_UP = 19;
    public static final int KEYCODE_DPAD_DOWN = 20;
    public static final int KEYCODE_DPAD_LEFT = 21;
    public static final int KEYCODE_DPAD_RIGHT = 22;
    public static final int KEYCODE_DPAD_CENTER = 23;
    public static final int KEYCODE_VOLUME_MUTE = 164;
    public static final int KEYCODE_VOLUME_UP = 24;
    public static final int KEYCODE_VOLUME_DOWN = 25;
    public static final int KEYCODE_POWER = 26;
    public static final int KEYCODE_HOME_PAGE = 3;
    public static final int KEYCODE_BACK_TRACK = 4;

    public static final int KEYCODE_SOURCE = 178;
    public static final int KEYCODE_MENU = 82;



    private static class KeyEventHelperHolder {
        private static final KeyEventHelper INSTANCE = new KeyEventHelper();

    }

    private KeyEventHelper() {
    }

    public static final KeyEventHelper getInstance() {
        return KeyEventHelperHolder.INSTANCE;
    }


    public void dealKeyEvent(String keyName, int keyValue) {
        Log.i(TAG, "this is dealKeyEvent start:" + keyName);
        switch (keyName) {
            case ControlConfig.COMMAND_SET_POWERSTATE:
                setPowerOff(keyValue);
//                setPowerBackLight(keyValue);
                break;
            case ControlConfig.COMMAND_SET_DIRECTION:
                setDirection(keyValue);
                break;
            case ControlConfig.COMMAND_SET_VOLUME:
                setVolume(keyValue);

                break;
            case ControlConfig.COMMAND_SET_HOMEPAGE:
                setHomePage();
                break;
            case ControlConfig.COMMAND_SET_CHANNEL:
                setChannel(keyValue);
                break;
            case ControlConfig.COMMAND_SET_BACKTRACK:
                setBackTrack();
                break;
            case ControlConfig.COMMAND_SET_MENU:
                setKeycodeMenu();
                break;
            case ControlConfig.COMMAND_SET_SOURCE:
                setKeycodeSource();
                break;

        }
        Log.i(TAG, "this is dealKeyEvent success");
    }

    private void setKeycodeMenu() {
        sendKeyThread(KEYCODE_MENU);
    }
    private void setKeycodeSource() {
        sendKeyThread(KEYCODE_SOURCE);
    }
    private void setBackTrack() {
        sendKeyThread(KEYCODE_BACK_TRACK);
    }

    private void setHomePage() {
        sendKeyThread(KEYCODE_HOME_PAGE);
    }

    private void setChannel(int keyValue) {
        switch (keyValue) {
            case 0:
                sendKeyThread(KEYCODE_CHANNEL_UP);
                break;
            case 1:
                sendKeyThread(KEYCODE_CHANNEL_DOWN);
                break;
        }
    }

    private void setDirection(int value) {
        switch (value) {
            case 0:
                sendKeyThread(KEYCODE_DPAD_CENTER);
                break;
            case 1:
                sendKeyThread(KEYCODE_DPAD_UP);
                break;
            case 2:
                sendKeyThread(KEYCODE_DPAD_DOWN);
                break;
            case 3:
                sendKeyThread(KEYCODE_DPAD_LEFT);
                break;
            case 4:
                sendKeyThread(KEYCODE_DPAD_RIGHT);
                break;

        }
    }

    /**
     * 正常关机
     * 0:关机
     * 1:开机
     */
    private void setPowerOff(int powerState) {
        Log.i("DEBUG_TS", "this is setPowerOff:" + powerState);
        String powerValue = String.valueOf(SystemProperties.get(PERSIST_POWER_STATUS));
        if (powerState == 1) {//开机
            Log.i("DEBUG_TS", "this is setPowerOff kai:" + powerValue);
            if (powerValue.equals("false")) {
                Log.i("DEBUG_TS", "this is setPowerOff kai:");
                sendKeyThread(KEYCODE_POWER);
                //SystemProperties.set(PERSIST_POWER_STATUS, "true");
            }

        } else {//关机
            Log.i("DEBUG_TS", "this is setPowerOff guan:" + powerValue);
            if (powerValue.equals("true")) {
                Log.i("DEBUG_TS", "this is setPowerOff guan:");
                sendKeyThread(KEYCODE_POWER);
                //SystemProperties.set(PERSIST_POWER_STATUS, "false");
            }
        }

    }


    private void setVolume(int value) {
        if (value == 101) {
            sendKeyThread(KEYCODE_VOLUME_UP);
        } else if (value == 102) {
            sendKeyThread(KEYCODE_VOLUME_DOWN);
        } else if (value == 103) {
            sendKeyThread(KEYCODE_VOLUME_MUTE);
        } else {
            setVolumeValue(value);
        }
    }

    private void setVolumeValue(int volumeValue) {
        try {
            AudioManager mAudioManager = (AudioManager) MyApplication.getAppContext().
                    getSystemService(Context.AUDIO_SERVICE);
            mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
                    volumeValue, AudioManager.FLAG_SHOW_UI);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private synchronized void setPowerBackLight(int powerState) {
        TTvFunctionManager mTvFunctionManager = TTvFunctionManager.getInstance(MyApplication.getAppContext());
        //亮熄屏幕
        mTvFunctionManager.setPowerBacklight(powerState == 0);
        try {
            if (powerState == 0) {//开机
                SystemProperties.set(PERSIST_POWER_STATUS, "true");
                if (!Constants.DEVICE_TYPE.contains(Constants.DEVICE_TYPE_972)) {
                    //setVolumeMute(false);
                }
            } else {//关机
                if (Constants.DEVICE_TYPE.contains(Constants.DEVICE_TYPE_972)) {
                    setHomePage();
                } else {
                    //setVolumeMute(true);
                    String topActName = getCurRunningTopActivityName();
                    Log.i("DEBUG_TS", "this is topActName:" + topActName);
                    if (!topActName.equalsIgnoreCase(KeyEventHelper.PACKAGE_HOME_ACTIVITY)) {
                        //app远程关机切换到主页
                        //setHomePage();
                        startHomeAct();
                    }

                    SystemProperties.set(PERSIST_POWER_STATUS, "false");
                }


            }
            Log.i("DEBUG_TS", "this is status:" + SystemProperties.get(PERSIST_POWER_STATUS));

        } catch (Exception e) {
            e.printStackTrace();
            Log.i("DEBUG_TS", "this is topActName: e:" + e.toString());
        }

    }

    //topActivity:com.tcl.tv.TVActivity
    public String getCurRunningTopActivityName() {
        try {
            ActivityManager mgr = (ActivityManager) MyApplication.getAppContext().getSystemService(Context.ACTIVITY_SERVICE);
            ActivityManager.RunningTaskInfo info = null;
            try {
                info = mgr.getRunningTasks(1).get(0);//launcher has the permission
            } catch (Exception e) {
                Log.d("DEBUG_TS", "have no permission to getCurRunningActivityPackageName");
            }

            if (info == null)
                return "";
            else {
                Log.d("DEBUG_TS", "topActivity:" + info.topActivity.getClassName());
                return info.topActivity.getClassName();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";

    }


    public void startHomeAct() {
        try {
            Intent intent = new Intent();
            intent.setComponent(new ComponentName(PACKAGE_HOME, PACKAGE_HOME_ACTIVITY));
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            MyApplication.getAppContext().startActivity(intent);
            Log.i("DEBUG_TS", "this is startHomeAct:");
            if (SystemProperties.get("persist.sys.bootactivity").equalsIgnoreCase("UI")) {
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


//    private void setVolumeMute(boolean isTrue) {
//        AudioManager audioManager = (AudioManager) MyApplication.getAppContext().getSystemService(Context.AUDIO_SERVICE);
//
//        if (isTrue) {
//            APIHelper.getInstance(MyApplication.getAppContext()).setAudioMuteStatus(true);
//            //sendKeyThread(KEYCODE_VOLUME_MUTE);
//        } else {
//            APIHelper.getInstance(MyApplication.getAppContext()).setAudioMuteStatus(false);
//        }
//
//
//    }


    public void sendKeyThread(final int keycode) {

        ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(2);
        executor.schedule(new Runnable() {
            @Override
            public void run() {
                sendKey(keycode);
            }
        }, 100, TimeUnit.MILLISECONDS);

    }

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

}
