package com.xugame.gameconsole.dialog.gamemenu;

import android.content.Context;
import android.graphics.Color;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.xugame.gameconsole.R;
import com.xugame.gameconsole.dialog.BaseDialog;
import com.xugame.gameconsole.emulator.ScreenType;
import com.xugame.gameconsole.util.DebugUtil;

import java.util.HashMap;

public class GameMenuDialog extends BaseDialog
        implements RadioGroup.OnCheckedChangeListener,
        View.OnClickListener {
    private static final String TAG = "GameMenuDialogTAG";
    private RadioGroup mRadioGroup;
    GameMenuDialogListener mListener;
    ScreenType mType = ScreenType.NORMAL;
    private TextView[] archiveTexts;
    private TextView[] readArchiveTexts;
    private Context mContext;
    private int mReadArchiveIndex = 0;//读取存档下标
    private LinearLayout mKeySettingBg;
    private Button mCommit;
    //UP/DOWN/LEFT/RIGHT/A/B/X/Y/L1/R1/L2/R2

    private String[] KEYNAMES = {
            "A",
            "X",
            "SELECT",
            "START",
            "UP",
            "DOWN",
            "LEFT",
            "RIGHT",
            "B",
            "Y",
            "L1",
            "R1",
    };
    private int[] KEYS = {
            KeyEvent.KEYCODE_J,
            KeyEvent.KEYCODE_L,
            KeyEvent.KEYCODE_3,
            KeyEvent.KEYCODE_1,
            KeyEvent.KEYCODE_W,
            KeyEvent.KEYCODE_S,
            KeyEvent.KEYCODE_A,
            KeyEvent.KEYCODE_D,
            KeyEvent.KEYCODE_K,
            KeyEvent.KEYCODE_U,
            KeyEvent.KEYCODE_I,
            KeyEvent.KEYCODE_O,
    };

    private Button mKeySwitch;
    private boolean isKeySettingRunning = false;
    private int keySettingIndex = 0;
    private RadioButton[] mKeyNumText;
    private TextView mKeyName;
    private RadioGroup mKeyRadioGroup;

    public GameMenuDialog(Context context, GameMenuDialogListener listener) {
        super(context, R.style.DialogNoPadding);
        this.mListener = listener;
        this.mContext = context;
        setContentView(R.layout.dialog_gamemenu_layout);
        Window window = this.getWindow();
        WindowManager.LayoutParams wLp = window.getAttributes();
        wLp.width = 1200;
        wLp.height = 832;
        wLp.dimAmount = 0.6f;//透明度
        window.setAttributes(wLp);
        this.initView();
    }

    private void initView() {
        mRadioGroup = findViewById(R.id.radio_gp_screen);
        mRadioGroup.setOnCheckedChangeListener(this);
        archiveTexts = new TextView[5];
        readArchiveTexts = new TextView[5];
        archiveTexts[0] = findViewById(R.id.archive_1);
        archiveTexts[1] = findViewById(R.id.archive_2);
        archiveTexts[2] = findViewById(R.id.archive_3);
        archiveTexts[3] = findViewById(R.id.archive_4);
        archiveTexts[4] = findViewById(R.id.archive_5);

        readArchiveTexts[0] = findViewById(R.id.read_archive_1);
        readArchiveTexts[1] = findViewById(R.id.read_archive_2);
        readArchiveTexts[2] = findViewById(R.id.read_archive_3);
        readArchiveTexts[3] = findViewById(R.id.read_archive_4);
        readArchiveTexts[4] = findViewById(R.id.read_archive_5);
        mKeySettingBg = findViewById(R.id.key_setting_bg);
        mKeySwitch = findViewById(R.id.key_setting_switch);
        mKeyName = findViewById(R.id.keyName);
        mCommit = findViewById(R.id.key_setting_commit);
        mKeyRadioGroup = findViewById(R.id.key_radio_grop);

        mKeySwitch.setOnClickListener(this);
        mKeyNumText = new RadioButton[KEYS.length];
        for (int i = 0; i < KEYS.length; i++) {
            RadioButton radioButton = new RadioButton(mContext);
            radioButton.setText(KEYNAMES[i]);
            radioButton.setTextColor(Color.BLACK);
            RadioGroup.LayoutParams llp = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.WRAP_CONTENT,
                    RadioGroup.LayoutParams.WRAP_CONTENT);
            llp.leftMargin = 10;
            mKeyRadioGroup.addView(radioButton, llp);

            final int index = i;
            radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                    if (b) {
                        keySettingIndex = index;
                        radioButton.setBackgroundColor(Color.GRAY);
                        isKeySettingRunning = true;
                    } else {
                        radioButton.setBackgroundColor(Color.WHITE);
                    }
                }
            });

            mKeyNumText[i] = radioButton;
        }

        //点击确定，上报新的按键
        mCommit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DebugUtil.i(TAG, "click commit");
                if (isKeySettingRunning) {
                    Toast.makeText(mContext, "当前处于编辑状态", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    if (mListener != null)
                        mListener.onKeySettingNums(KEYS);
                }
            }
        });

        for (int i = 0; i < archiveTexts.length; i++) {
            final int tempIndex = i;
            archiveTexts[i].setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (mListener != null && mListener.onSaveState(tempIndex))
                        // todo: save state error handler
                        ;
                    dismiss();
                }
            });
        }

        for (int i = 0; i < readArchiveTexts.length; i++) {
            final int tempIndex = i;
            readArchiveTexts[i].setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mReadArchiveIndex = tempIndex;
                    if (mListener != null && mListener.onLoadState(tempIndex))
                        // todo: load state error handler
                        ;
                    dismiss();
                }
            });
        }

        findViewById(R.id.ratioCoreButton).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mListener != null)
                    mListener.onSetRatio(0);

                dismiss();
            }
        });

        findViewById(R.id.ratioFullscreenButton).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mListener != null)
                    mListener.onSetRatio(1);

                dismiss();
            }
        });

        findViewById(R.id.ratioCustomButton).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mListener != null)
                    mListener.onSetRatio(2);

                dismiss();
            }
        });

        findViewById(R.id.resume_game).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mListener != null)
                    mListener.onResumeGame(mType, mReadArchiveIndex);
                dismiss();
            }
        });
        findViewById(R.id.stop_game).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mListener != null)
                    mListener.onExitGame();
                dismiss();
            }
        });
    }

    @Override
    public void onCheckedChanged(RadioGroup radioGroup, int i) {
        if (radioGroup.getCheckedRadioButtonId() == R.id.normal) {
            mType = ScreenType.NORMAL;
        } else if (radioGroup.getCheckedRadioButtonId() == R.id.sai_2x) {
            mType = ScreenType.SAI_2X;
        } else if (radioGroup.getCheckedRadioButtonId() == R.id.scanline_game) {
            mType = ScreenType.SCANLINE;
        }
    }

    @Override
    public boolean dispatchKeyEvent(@NonNull KeyEvent event) {
        if (isKeySettingRunning) {
            if (event.getAction() == KeyEvent.ACTION_DOWN) {
                int devicesID = event.getDeviceId();
                String devicesName = event.getDevice().getName();
                int keyCode = event.getKeyCode();
                mKeyName.setText("按键ID:" + devicesID + "   设备名：" + devicesName + "  keycode:" + keyCode);
                if (keySettingIndex < KEYS.length) {
                    boolean isSwap = false;//是否交换键值
                    mKeyNumText[keySettingIndex].setBackgroundColor(Color.WHITE);
                    for (int i = 0; i < KEYS.length; i++) {
                        if (keyCode == KEYS[i] && keySettingIndex != i) {
                            int temp = KEYS[keySettingIndex];
                            KEYS[i] = temp;
                            KEYS[keySettingIndex] = keyCode;
                            isSwap = true;
                        }
                    }
                    if (!isSwap)//没有相同键值则直接赋值
                        KEYS[keySettingIndex] = keyCode;
                }
                isKeySettingRunning = false;
                String tempKeyStr = "";
                for (int i=0;i<KEYS.length;i++) {
                    tempKeyStr += KEYS[i] + "-";
                }
                DebugUtil.i(TAG, "key=" + tempKeyStr);
            }
            return super.dispatchKeyEvent(event);
        } else {
            return super.dispatchKeyEvent(event);
        }

    }


    @Override
    public void onClick(View view) {
        if (view == mKeySwitch) {
            isKeySettingRunning = !isKeySettingRunning;
            mKeySwitch.setText((isKeySettingRunning != true ? "开始设置按键" : "停止设置按键"));
        }
    }
}
