package com.xugame.gameconsole.monitor;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.text.TextUtils;

import com.xugame.gameconsole.util.DebugUtil;

public class EmulatorMonitor {

    private final String TAG = "EmulatorMonitor";
    public static final String EMULATOR_SAVE_STATE_ACTION = "EMULATOR_SAVE_STATE_ACTION";
    public static final String EMULATOR_LOAD_STATE_ACTION = "EMULATOR_LOAD_STATE_ACTION";

    public static final String EMULATOR_SAVE_STATE_RESULT_ACTION = "EMULATOR_SAVE_STATE_RESULT_ACTION";//用于存档结果回调


    private static final String SYSTEM_REASON = "reason";
    private static final String SYSTEM_HOME_KEY = "homekey";
    private static final String SYSTEM_HOME_RECENT_APPS = "recentapps";

    private Context mContext;
    private BroadcastReceiver mDeviceKeyReceiver = null;
    private EmulatorMonitorListener mListener;

    public EmulatorMonitor(Context context, EmulatorMonitorListener listener) {
        mContext = context;
        mListener = listener;
        mDeviceKeyReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (intent != null) {
                    parserIntent(intent);
                }
            }
        };
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        filter.addAction(EMULATOR_SAVE_STATE_ACTION);
        filter.addAction(EMULATOR_LOAD_STATE_ACTION);
        mContext.registerReceiver(mDeviceKeyReceiver,
                filter);
    }


    private void parserIntent(Intent intent) {
        DebugUtil.i(TAG, "" + intent.getAction());
        if (intent.getAction().equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
            String reason = intent.getStringExtra(SYSTEM_REASON);
            if (!TextUtils.isEmpty(reason)) {
                if (SYSTEM_HOME_KEY.equals(reason)) {
                    mListener.onHomeClick();
                } else if (SYSTEM_HOME_RECENT_APPS.equals(reason)) {
                    mListener.onRecentClick();
                }
            }
        } else if (intent.getAction().equals(EMULATOR_SAVE_STATE_ACTION)) {
            int stateIndex = intent.getIntExtra("saveState", -1);
            if (stateIndex >= 0 && mListener != null) {
                mListener.onMenuSaveState(stateIndex);
            }
        } else if (intent.getAction().equals(EMULATOR_LOAD_STATE_ACTION)) {
            int stateIndex = intent.getIntExtra("loadState", -1);
            if (stateIndex >=0 && mListener != null) {
                mListener.onMenuLoadState(stateIndex);
            }
        }
    }


    public void unregister() {
        if (mDeviceKeyReceiver != null) {
            mContext.unregisterReceiver(mDeviceKeyReceiver);
            mDeviceKeyReceiver = null;
        }
    }

}
