package com.xugame.gameconsole.emulator;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.hardware.input.InputManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;

import com.retroarch.browser.retroactivity.AspectRatio;
import com.xugame.app.AppSystem;
import com.xugame.app.EnvironmentCallback;
import com.xugame.bean.InputCode;
import com.xugame.bean.InputDescriptorBean;
import com.xugame.bean.SystemAVInfo;
import com.xugame.gameconsole.dialog.LoadingDialog;
import com.xugame.gameconsole.dialog.gamemenu.GameMenuDialog;
import com.xugame.gameconsole.dialog.gamemenu.GameMenuDialogListener;
import com.xugame.gameconsole.monitor.EmulatorMonitor;
import com.xugame.gameconsole.monitor.EmulatorMonitorListener;
import com.xugame.gameconsole.preferences.ConfigFile;
import com.xugame.gameconsole.preferences.UserPreferences;
import com.xugame.gameconsole.util.DebugUtil;
import com.xugame.gameconsole.util.Util;

import java.io.File;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;

//private void parserIntent() {
//        Intent intent = getIntent();
//        romPath = intent.getStringExtra("rom_path");
//        romPath = intent.getStringExtra("rom_path");
//        libsPath = intent.getStringExtra("lib_path");
//        configPath = intent.getStringExtra("config_path");
//        }
public class RetroArchEmulatorActivity extends RetroActivityCamera
        implements EmulatorMonitorListener {
    private static final String TAG = "RetroArchEmulatorActivityTAG";
    private ScreenType mScreenType = ScreenType.NORMAL;
    private boolean mUpdateScreen = false;
    // If set to true then Retroarch will completely exit when it loses focus
    private boolean quitfocus = false;

    private AppSystem system = null;
    private boolean isBusy = false;
    private LoadingDialog mLoadingDialog;
    private EmulatorMonitor mEmulatorMonitor;
    private String mRomPath;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        system = new AppSystem();
        mRomPath = getIntent().getStringExtra("ROM");
        callback = new EnvironmentCallback() {
            @Override
            public void setInputDescriptors(InputDescriptorBean[] descriptors) {
                for (int i = 0; i < descriptors.length; i++) {
                    Log.i(
                            "EnvironmentCallback",
                            "i: " + i
                                    + ", port: " + descriptors[i].getPort()
                                    + ", device: " + descriptors[i].getDevice()
                                    + ", index: " + descriptors[i].getIndex()
                                    + ", id: " + descriptors[i].getId()
                                    + ", desc: " + descriptors[i].getDescription()
                    );

                    if (descriptors[i].getPort() >= AppSystem.MAX_USERS)
                        continue;

                    if (descriptors[i].getId() >= 16)
                        continue;

                    if (descriptors[i].getDevice() == AppSystem.DEVICE_JOYPAD) {
                        system.inputDescriptors[descriptors[i].getPort()]
                                [descriptors[i].getId()] = descriptors[i].getDescription();
                    } else if (descriptors[i].getDevice() == AppSystem.DEVICE_ANALOG) {
                        if (descriptors[i].getId() == AppSystem.DEVICE_ID_ANALOG_X) {
                            if (descriptors[i].getIndex() == AppSystem.DEVICE_INDEX_ANALOG_LEFT) {
                                system.inputDescriptors[descriptors[i].getPort()]
                                        [InputCode.AnalogBindSet.ANALOG_LEFT_X_PLUS] = descriptors[i].getDescription();
                                system.inputDescriptors[descriptors[i].getPort()]
                                        [InputCode.AnalogBindSet.ANALOG_LEFT_X_MINUS] = descriptors[i].getDescription();
                            } else if (descriptors[i].getIndex() == AppSystem.DEVICE_INDEX_ANALOG_RIGHT) {
                                system.inputDescriptors[descriptors[i].getPort()]
                                        [InputCode.AnalogBindSet.ANALOG_RIGHT_X_PLUS] = descriptors[i].getDescription();
                                system.inputDescriptors[descriptors[i].getPort()]
                                        [InputCode.AnalogBindSet.ANALOG_RIGHT_X_MINUS] = descriptors[i].getDescription();
                            }
                        } else if (descriptors[i].getId() == AppSystem.DEVICE_ID_ANALOG_Y) {
                            if (descriptors[i].getIndex() == AppSystem.DEVICE_INDEX_ANALOG_LEFT) {
                                system.inputDescriptors[descriptors[i].getPort()]
                                        [InputCode.AnalogBindSet.ANALOG_LEFT_Y_PLUS] = descriptors[i].getDescription();
                                system.inputDescriptors[descriptors[i].getPort()]
                                        [InputCode.AnalogBindSet.ANALOG_LEFT_Y_MINUS] = descriptors[i].getDescription();
                            } else if (descriptors[i].getIndex() == AppSystem.DEVICE_INDEX_ANALOG_RIGHT) {
                                system.inputDescriptors[descriptors[i].getPort()]
                                        [InputCode.AnalogBindSet.ANALOG_RIGHT_Y_PLUS] = descriptors[i].getDescription();
                                system.inputDescriptors[descriptors[i].getPort()]
                                        [InputCode.AnalogBindSet.ANALOG_RIGHT_Y_MINUS] = descriptors[i].getDescription();
                            }
                        } else if (descriptors[i].getId() == AppSystem.DEVICE_ID_JOYPAD_L2
                                || descriptors[i].getId() == AppSystem.DEVICE_ID_JOYPAD_R2
                        ) {
                            if (descriptors[i].getIndex() == AppSystem.DEVICE_INDEX_ANALOG_BUTTON) {
                                system.inputDescriptors[descriptors[i].getPort()]
                                        [descriptors[i].getId()] = descriptors[i].getDescription();
                            }
                        }
                    }
                }

                system.hasInputDescriptors = true;
            }

            @Override
            public void setSystemAVInfo(SystemAVInfo systemAVInfo) {
                system.systemAVInfo = systemAVInfo;
                Log.i("EnvironmentCallback", system.systemAVInfo.toString());
            }

            @Override
            public void setGeometry(SystemAVInfo.GameGeometry geometry) {
                system.systemAVInfo.setGeometry(geometry);
                Log.i("EnvironmentCallback", geometry.toString());
            }

            @Override
            public void contentLoaded() {
                Log.i("EnvironmentCallback", "Content Loaded");
//                testSetKey2();
            }

            @Override
            public void saveStateCallback(int error) {
                Log.i("EnvironmentCallback", "saveStateCallback: " + error);
                Intent intent = new Intent();
                intent.setAction(EmulatorMonitor.EMULATOR_SAVE_STATE_RESULT_ACTION);
                intent.putExtra("save_state_flag", error == 0);
                sendBroadcast(intent);
            }
        };
        mEmulatorMonitor = new EmulatorMonitor(this, this);
    }

    @Override
    public void showLocalExitDialog() {
//        runOnUiThread(new Runnable() {
//            @Override
//            public void run() {
//                showDialog();
//            }
//        });

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (!isBusy) {
                    isBusy = true;
                    if (mLoadingDialog == null)
                        mLoadingDialog = new LoadingDialog(RetroArchEmulatorActivity.this);
                    if (mLoadingDialog.isShowing())
                        return;
                    else
                        mLoadingDialog.show();
                    Intent intent = new Intent();//调出主菜单UI
                    if (system != null && system.systemAVInfo != null) {
                        int w = system.systemAVInfo.getGeometry().getBaseWidth();
                        int h = system.systemAVInfo.getGeometry().getBaseHeight();
                        intent.putExtra("game_x", w);
                        intent.putExtra("game_y", h);
                    }
                    ComponentName componentName = new ComponentName("com.xugame.gameconsoleMenu",
                            "com.xugame.gameconsole.dialog.localgamesetting.LocalGameSettingDialog");
                    intent.putExtra("rompath", mRomPath);
                    intent.setComponent(componentName);
                    startActivityForResult(intent, 200);
                    DebugUtil.i(TAG, "showLocalExitDialog");
                }
            }
        });

    }

    @Override
    public void onPause() {
        super.onPause();
        isBusy = false;
        DebugUtil.i(TAG, "onPause");
    }


    @Override
    public void onResume() {
        super.onResume();

        setSustainedPerformanceMode(sustainedPerformanceMode);

        if (Build.VERSION.SDK_INT >= 19) {
            // Immersive mode

            // Constants from API > 14
            final int API_SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
            final int API_SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
            final int API_SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
            final int API_SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
            final int API_SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000;

            View thisView = getWindow().getDecorView();
            thisView.setSystemUiVisibility(API_SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | API_SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | API_SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | API_SYSTEM_UI_FLAG_FULLSCREEN
                    | API_SYSTEM_UI_FLAG_IMMERSIVE_STICKY);

            // Check for Android UI specific parameters
            Intent retro = getIntent();

            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
                String refresh = retro.getStringExtra("REFRESH");

                // If REFRESH parameter is provided then try to set refreshrate accordingly
                if (refresh != null) {
                    WindowManager.LayoutParams params = getWindow().getAttributes();
                    params.preferredRefreshRate = Integer.parseInt(refresh);
                    getWindow().setAttributes(params);
                }
            }

            // If QUITFOCUS parameter is provided then enable that Retroarch quits when focus is lost
            quitfocus = retro.hasExtra("QUITFOCUS");

            // If HIDEMOUSE parameters is provided then hide the mourse cursor
            // This requires NVIDIA Android extensions (available on NVIDIA Shield), if they are not
            // available then nothing will be done
            if (retro.hasExtra("HIDEMOUSE")) hideMouseCursor();
            int screenMode = retro.getIntExtra("screenMode", 0);
//            if(screenMode>=0&&screenMode<3){
//                switch (screenMode) {
//                    case 0:
//                        setAspectRatio(AspectRatio.ASPECT_RATIO_CORE.getValue());
//                        break;
//                    case 1:
//                        setAspectRatio(AspectRatio.ASPECT_RATIO_FULL.getValue());
//                        break;
//                    case 2:
//                        setAspectRatio(AspectRatio.ASPECT_RATIO_CUSTOM.getValue());
//                        setCustomViewPort(Util.getSize(420), Util.getSize(87), Util.getSize(1080), Util.getSize(810));
//                        break;
//                }
//            }
        }

        //Checks if Android versions is above 9.0 (28) and enable the screen to write over notch if the user desires
        if (Build.VERSION.SDK_INT >= 28) {
            ConfigFile configFile = new ConfigFile(UserPreferences.getDefaultConfigPath(this));
            try {
                if (configFile.getBoolean("video_notch_write_over_enable")) {
                    getWindow().getAttributes().layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
                }
            } catch (Exception e) {
                Log.w("Key doesn't exist yet.", e.getMessage());
            }
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mEmulatorMonitor != null)
            mEmulatorMonitor.unregister();
    }

    public void hideMouseCursor() {

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
            // Check for NVIDIA extensions and minimum SDK version
            Method mInputManager_setCursorVisibility;
            try {
                mInputManager_setCursorVisibility =
                        InputManager.class.getMethod("setCursorVisibility", boolean.class);
            } catch (NoSuchMethodException ex) {
                return; // Extensions were not available so do nothing
            }

            // Hide the mouse cursor
            InputManager inputManager = (InputManager) getSystemService(Context.INPUT_SERVICE);
            try {
                mInputManager_setCursorVisibility.invoke(inputManager, false);
            } catch (InvocationTargetException ite) {
            } catch (IllegalAccessException iae) {
            }
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        DebugUtil.i(TAG, "onStop");
        // If QUITFOCUS parameter was set then completely exit Retroarch when focus is lost
        if (quitfocus) System.exit(0);
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        DebugUtil.i(TAG, "" + event.getKeyCode());
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK
        ) {
//            showDialog();
            Intent intent = new Intent();//调出主菜单UI
            ComponentName componentName = new ComponentName("com.xugame.gameconsoleMenu",
                    "com.xugame.gameconsole.dialog.localgamesetting.LocalGameSettingDialog");
            intent.setComponent(componentName);
            startActivityForResult(intent, 200);
//            setScan();
            return super.dispatchKeyEvent(event);
        }

        return super.dispatchKeyEvent(event);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        DebugUtil.i(TAG, "onKeyDown=" + event.getKeyCode());
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        if (mUpdateScreen) {
            switch (mScreenType) {
                case NORMAL:
                    switchFilter("/data/user/0/com.xugame.gameconsole/filters/video/Scale2x.filt");
                    break;
                case SAI_2X:
                    switchFilter("/data/user/0/com.xugame.gameconsole/filters/video/LQ2x.filt");
                    break;
                case SCANLINE:
                    switchFilter("/data/user/0/com.xugame.gameconsole/filters/video/EPX.filt");
                    break;
            }
        }
        if (!hasFocus) {
            if (mLoadingDialog != null) {
                mLoadingDialog.dismiss();
            }
        }
        DebugUtil.i(TAG, "onWindowFocusChanged" + hasFocus);
        super.onWindowFocusChanged(hasFocus);
    }

    private void showDialog() {
        GameMenuDialog menuDialog = new GameMenuDialog(this,
                new GameMenuDialogListener() {
                    @Override
                    public void onExitGame() {
                        exitLocalGame();
                        finish();
                    }

                    @Override
                    public void onResumeGame(ScreenType type, int archiveIndex) {
                        mScreenType = type;
                        mUpdateScreen = true;
                        gameDialogClosed();
                    }

                    @Override
                    public boolean onSaveState(int stateIndex) {
                        // Toast.makeText(mContext, "写入存档" + stateIndex, Toast.LENGTH_SHORT).show();
                        return saveState(stateIndex);
                    }

                    @Override
                    public boolean onLoadState(int stateIndex) {
                        // Toast.makeText(mContext,"读取存档"+stateIndex,Toast.LENGTH_SHORT).show();
                        return loadState(stateIndex);
                    }

                    @Override
                    public void onKeySettingNums(int[] keys) {
                        for (int i = 0; i < keys.length; i++) {
                            setInputKeys(0, i, keys[i]);
                        }
                        saveOverrideConfig();
                    }

                    @Override
                    public void onSetRatio(int type) {
                        switch (type) {
                            case 0:
                                setAspectRatio(AspectRatio.ASPECT_RATIO_CORE.getValue());
                                break;
                            case 1:
                                setAspectRatio(AspectRatio.ASPECT_RATIO_FULL.getValue());
                                break;
                            case 2:
                                setAspectRatio(AspectRatio.ASPECT_RATIO_CUSTOM.getValue());
                                setCustomViewPort(100, 100, 480, 320);
                                break;
                        }
                    }
                });
        menuDialog.setCanceledOnTouchOutside(true);
        menuDialog.show();


//        AlertDialog.Builder alertDialog = new ProgressDialog.Builder(this)
//                .setTitle("Yes/No")
//                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        clickBack();
//                        dialog.dismiss();
//                    }
//                })
//                .setNegativeButton("No", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        dialog.dismiss();
//                    }
//                })
//                .setMessage("退出游戏？");
//        alertDialog.show();
    }

    private int mScreen = -1;
    private int mScanline = -1;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        DebugUtil.i(TAG,"requestCode="+requestCode+"resultCode="+resultCode);
        if (requestCode == 200) {
            if (resultCode == 201) {//继续游戏
                gameDialogClosed();
//                testSetKey2();
                if (data != null) {
                    //增加完美像素单独开关，避免混淆
                    boolean isPixelPerfect = data.getBooleanExtra("is_pixelperfect", false);
//                    isPixelPerfect = true;
                    if (!isPixelPerfect) {
                        int scanLine = data.getIntExtra("scanLine", 0);
                        int screen = data.getIntExtra("screen", 0);
                        DebugUtil.i(TAG, "scanline=" + scanLine + "screen=" + screen);
//                        if (mScreen != screen) {
                        mScreen = screen;
                        if (screen >= 0 && screen < 3) {
                            DebugUtil.i(TAG, "设置screen" + screen);
                            switch (screen) {

                                case 0:
                                    setAspectRatio(AspectRatio.ASPECT_RATIO_CORE.getValue());
//                                        setCustomViewPort(Util.getSize(420), Util.getSize(87), Util.getSize(1080), Util.getSize(810));
                                    break;
                                case 1:
                                    setAspectRatio(AspectRatio.ASPECT_RATIO_4_3.getValue());
                                    break;
                                case 2:
                                    setAspectRatio(AspectRatio.ASPECT_RATIO_FULL.getValue());
                                    break;

                            }
                        }
//                        }
//                        if (mScanline != scanLine) {
                        mScanline = scanLine;
                        if (scanLine >= 0 && scanLine < 4) {
                            DebugUtil.i(TAG, "设置scanLine" + scanLine + ScreenType.values()[scanLine]);

                            switch (ScreenType.values()[scanLine]) {
                                case NORMAL:
                                    switchFilter(null);
                                    break;
                                case SAI_2X:
                                    switchFilter("/data/user/0/com.xugame.gameconsole/filters/video/Scale2x.filt");
                                    break;
                                case SCANLINE:
                                    switchFilter("/data/user/0/com.xugame.gameconsole/filters/video/Scanline2x.filt");
                                    break;
                                case EPX:
                                    switchFilter("/data/user/0/com.xugame.gameconsole/filters/video/EPX.filt");
                                    break;
                            }
                        }
//                        }
                    } else {
                        int multiple = data.getIntExtra("multiple", -1);
                        mScanline = -1;
                        mScreen = -1;
                        DebugUtil.i(TAG, "multiple=" + multiple);
                        if (multiple >= 2 && multiple <= 5) {
                            resetScreenForPerfect(multiple);
                        }
                    }


                }
            } else if (resultCode == 0) {
                exitLocalGame();
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void testSetKey() {
        int[] javaKey = {
                InputCode.JoypadBindKeySet.JOYPAD_BTN_A,//轻拳
                InputCode.JoypadBindKeySet.JOYPAD_BTN_B,//重拳
                108,
                109,
                InputCode.JoypadBindKeySet.JOYPAD_AXIS_X_PLUS,
                InputCode.JoypadBindKeySet.JOYPAD_AXIS_X_MINIS,
                InputCode.JoypadBindKeySet.JOYPAD_AXIS_Y_PLUS,
                InputCode.JoypadBindKeySet.JOYPAD_AXIS_Y_MINIS,
                99,//轻脚
                100,//重脚
                98,
                101,
                103,
                104,
                105,
                106
        };
        int[] emulatorKey = {
                InputCode.JoypadBindSet.JOYPAD_B,
                InputCode.JoypadBindSet.JOYPAD_Y,
                InputCode.JoypadBindSet.JOYPAD_SELECT,
                InputCode.JoypadBindSet.JOYPAD_START,
                InputCode.JoypadBindSet.JOYPAD_UP,
                InputCode.JoypadBindSet.JOYPAD_DOWN,
                InputCode.JoypadBindSet.JOYPAD_LEFT,
                InputCode.JoypadBindSet.JOYPAD_RIGHT,
                InputCode.JoypadBindSet.JOYPAD_A,
                InputCode.JoypadBindSet.JOYPAD_X,
                InputCode.JoypadBindSet.JOYPAD_L,
                InputCode.JoypadBindSet.JOYPAD_R,
                InputCode.JoypadBindSet.JOYPAD_L2,
                InputCode.JoypadBindSet.JOYPAD_R2,
                InputCode.JoypadBindSet.JOYPAD_L3,
                InputCode.JoypadBindSet.JOYPAD_R3,
        };
        setJoystickBindNative(0, javaKey, emulatorKey);
    }


    private void testSetKey2() {
        int tempKeys[] = new int[35];
        int tempAxis[] = new int[35];
        for (int i = 0; i < tempKeys.length; i++) {
            tempKeys[i] = 0;

            tempAxis[i] = 0;
        }

        int[] keys = {//纯按键
                InputCode.JoypadBindKeySet.JOYPAD_BTN_A,//轻拳
                InputCode.JoypadBindKeySet.JOYPAD_BTN_B,//重拳
                108,
                109,
                InputCode.JoypadBindKeySet.JOYPAD_HAT_DOWN,
                InputCode.JoypadBindKeySet.JOYPAD_HAT_UP,
                InputCode.JoypadBindKeySet.JOYPAD_HAT_LEFT,
                InputCode.JoypadBindKeySet.JOYPAD_HAT_RIGHT,
                99,//轻脚
                100,//重脚
                98,
                101,
                103,
                104,
                105,
                106
        };
        for (int i = 0; i < keys.length; i++) {
            tempKeys[i] = keys[i];
        }
        int[] axiss = {//轴
                -1,
                -1,
                -1,
                -1,
                InputCode.JoypadBindKeySet.JOYPAD_AXIS_Y_MINIS,
                InputCode.JoypadBindKeySet.JOYPAD_AXIS_Y_PLUS,
                InputCode.JoypadBindKeySet.JOYPAD_AXIS_X_MINIS,
                InputCode.JoypadBindKeySet.JOYPAD_AXIS_X_PLUS,
                InputCode.JoypadBindKeySet.JOYPAD_AXIS_Z_PLUS,
                InputCode.JoypadBindKeySet.JOYPAD_AXIS_Z_MINIS,
        };
        for (int i = 0; i < axiss.length; i++) {
            tempAxis[i] = axiss[i];
        }
        setJoystickBindNative(0, tempKeys, tempAxis);
    }


    private void resetScreenForPerfect(int multiple) {
        if (system != null && system.systemAVInfo != null) {
            int w = system.systemAVInfo.getGeometry().getBaseWidth();
            int h = system.systemAVInfo.getGeometry().getBaseHeight();
            int screenX = Util.getScreenWidth();//屏幕真实大小
            int screenY = Util.getScreenHeight();
            int gameX = w * multiple;
            int gameY = h * multiple;

            setCustomViewPort((screenX - gameX) / 2, (screenY - gameY) / 2, gameX, gameY);
//            setCustomWidth(gameX);
//            setCustomHeight(gameY);

            File file = new File("/data/user/0/com.xugame.gameconsole/filters/video/Normal" + multiple + "x.filt");
            if (!file.exists()) {
                DebugUtil.i(TAG, "file not found");
                return;
            }
            setAspectRatio(AspectRatio.ASPECT_RATIO_CUSTOM.getValue());
            switchFilter("/data/user/0/com.xugame.gameconsole/filters/video/Normal"
                    + multiple + "x.filt");
            DebugUtil.i(TAG, "屏幕分辨率：" + screenX + "x" + screenY + "\n游戏原始WxH=" + w +
                    "x" + h + "\n设置宽高：" + gameX + "x" + gameY + "\nmultiple" + multiple);
        }
//        if (system != null && system.systemAVInfo != null) {
//            int w = system.systemAVInfo.getGeometry().getBaseWidth();
//            int h = system.systemAVInfo.getGeometry().getBaseHeight();
//
//            int screenX = Util.getScreenWidth();//屏幕真实大小
//            int screenY = Util.getScreenHeight();
//
//            int multiple = -1;//动态统一缩放倍数
//
//            int gameX = -1;
//            int gameY = -1;
//            if (screenX > screenY) {//屏幕宽为最大值
//                multiple = screenY / h;
//                gameY = multiple * h;//以高为准
//                gameX = (gameY * w) / h;
//            } else if (screenX < screenY) {//屏幕高为最大值
//                multiple = screenX / w;
//                gameX = multiple * w;//以宽为准
//                gameY = (gameX * h) / w;
//            } else if (screenX == screenY) {//以最小倍数为准
//                int tempX = screenX / w * w;
//                int tempY = screenY / h * h;
//                if (tempX > tempY) {
//                    multiple = tempY;
//                    gameY = tempY * h;
//                    gameX = (gameY * w) / h;
//                } else if (tempX < tempY) {
//                    multiple = tempX;
//                    gameX = tempX * w;
//                    gameY = (gameX * h) / w;
//                } else if (tempX == tempY) {
//                    multiple = tempX;
//                    gameX = tempX * w;
//                    gameY = tempY * h;
//                }
//            }
//            if (multiple <= 0)
//                return;
//
//            File file = new File("/data/user/0/com.xugame.gameconsole/filters/video/Normal" + multiple + "x.filt");
//            if (!file.exists()) {
//                DebugUtil.i(TAG, "file not found");
//                return;
//            }
//
//            setAspectRatio(AspectRatio.ASPECT_RATIO_CUSTOM.getValue());
//
//            setCustomViewPort((screenX - gameX) / 2, (screenY - gameY) / 2, gameX, gameY);
////            setCustomWidth(gameX);
////            setCustomHeight(gameY);
//
//            switchFilter("/data/user/0/com.xugame.gameconsole/filters/video/Normal"
//                    + multiple + "x.filt");
//
//        }
    }

    @Override
    public void onHomeClick() {
        DebugUtil.i(TAG, "onHomeClick");
    }

    @Override
    public void onRecentClick() {
        DebugUtil.i(TAG, "onRecentClick");
    }

    @Override
    public void onMenuSaveState(int index) {
        DebugUtil.i(TAG, "saveState" + index);
        if (index >= 0 && index < 10) {
            saveState(index);
//            if (saveState(index)) {
//                Intent intent = new Intent();
//                intent.setAction(EmulatorMonitor.EMULATOR_SAVE_STATE_ACTION);
//                intent.putExtra("save_state_flag", true);
//                this.sendBroadcast(intent);
//            }
        }
    }

    @Override
    public void onMenuLoadState(int index) {
        DebugUtil.i(TAG, "loadState" + index);
        if (index >= 0 && index < 10) {
            if (loadState(index)) {
                Intent intent = new Intent();
                intent.setAction(EmulatorMonitor.EMULATOR_LOAD_STATE_ACTION);
                intent.putExtra("load_state_flag", true);
                this.sendBroadcast(intent);
            }
        }
    }
}
