package com.xugame.gameconsole;

import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.media.AudioManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.xugame.gameconsole.emulator.RetroArchEmulatorActivity;
import com.xugame.gameconsole.preferences.UserPreferences;
import com.xugame.gameconsole.util.Util;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends PreferenceActivity implements View.OnClickListener {
    private EditText mETRom, mETLib, mETConfig;
    private Button mBtnLocalGame, mBtnNetP1, mBtnNetP2;

    final private int REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS = 124;
    public static String PACKAGE_NAME;
    boolean checkPermissions = false;

    public void showMessageOKCancel(String message, DialogInterface.OnClickListener onClickListener)
    {
        new AlertDialog.Builder(this).setMessage(message)
                .setPositiveButton("OK", onClickListener).setCancelable(false)
                .setNegativeButton("Cancel", null).create().show();
    }

    private boolean addPermission(List<String> permissionsList, String permission)
    {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M)
        {
            if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED)
            {
                permissionsList.add(permission);

                // Check for Rationale Option
                if (!shouldShowRequestPermissionRationale(permission))
                    return false;
            }
        }

        return true;
    }

    public void checkRuntimePermissions()
    {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M)
        {
            // Android 6.0+ needs runtime permission checks
            List<String> permissionsNeeded = new ArrayList<String>();
            final List<String> permissionsList = new ArrayList<String>();

            if (!addPermission(permissionsList, Manifest.permission.READ_EXTERNAL_STORAGE))
                permissionsNeeded.add("Read External Storage");
            if (!addPermission(permissionsList, Manifest.permission.WRITE_EXTERNAL_STORAGE))
                permissionsNeeded.add("Write External Storage");

            if (permissionsList.size() > 0)
            {
                checkPermissions = true;

                if (permissionsNeeded.size() > 0)
                {
                    // Need Rationale
                    Log.i("MainMenuActivity", "Need to request external storage permissions.");

                    String message = "You need to grant access to " + permissionsNeeded.get(0);

                    for (int i = 1; i < permissionsNeeded.size(); i++)
                        message = message + ", " + permissionsNeeded.get(i);

                    showMessageOKCancel(message,
                            new DialogInterface.OnClickListener()
                            {
                                @Override
                                public void onClick(DialogInterface dialog, int which)
                                {
                                    if (which == AlertDialog.BUTTON_POSITIVE)
                                    {
                                        requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
                                                REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);

                                        Log.i("MainMenuActivity", "User accepted request for external storage permissions.");
                                    }
                                }
                            });
                }
                else
                {
                    requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
                            REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);

                    Log.i("MainMenuActivity", "Requested external storage permissions.");
                }
            }
        }

        if (!checkPermissions)
        {
            finalStartup();
        }
    }

    public void finalStartup()
    {
        final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        Intent retro = new Intent(this, RetroArchEmulatorActivity.class);

//        retro.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//        retro.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        startRetroActivity(
                retro,
                romPath,
//                prefs.getString("libretro_path", getApplicationInfo().dataDir + "/cores/fbalpha2012_neogeo_libretro_android.so"),
                prefs.getString("libretro_path", corePath),
                UserPreferences.getDefaultConfigPath(this),
                Settings.Secure.getString(getContentResolver(), Settings.Secure.DEFAULT_INPUT_METHOD),
                getApplicationInfo().dataDir,
                getApplicationInfo().sourceDir);
        startActivity(retro);
        finish();
    }
    public static void startRetroActivity(Intent retro, String contentPath, String corePath,
                                          String configFilePath, String imePath, String dataDirPath, String dataSourcePath)
    {
        if (contentPath != null) {
            retro.putExtra("ROM", contentPath);
        }
        retro.putExtra("LIBRETRO", corePath);
        retro.putExtra("CONFIGFILE", configFilePath);
        retro.putExtra("IME", imePath);
        retro.putExtra("DATADIR", dataDirPath);
        retro.putExtra("APK", dataSourcePath);
        retro.putExtra("SDCARD", Environment.getExternalStorageDirectory().getAbsolutePath());
        String external = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/" + PACKAGE_NAME + "/files";
        retro.putExtra("EXTERNAL", external);
        Log.i("TEST_STAT","rompath="+contentPath+"\ncorePath="+corePath+"\n"+"configFilePath="+configFilePath+"\nimePath="+imePath
                +"\nDATADIR="+dataDirPath+"\nAPK="+dataSourcePath+
                "\nSDCARD="+Environment.getExternalStorageDirectory().getAbsolutePath()+"\nEXTERNAL="
                +external);
        retro.putExtra("screenMode",screenMode);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults)
    {
        switch (requestCode)
        {
            case REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS:
                for (int i = 0; i < permissions.length; i++)
                {
                    if(grantResults[i] == PackageManager.PERMISSION_GRANTED)
                    {
                        Log.i("MainMenuActivity", "Permission: " + permissions[i] + " was granted.");
                    }
                    else
                    {
                        Log.i("MainMenuActivity", "Permission: " + permissions[i] + " was not granted.");
                    }
                }

                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
                break;
        }

        finalStartup();
    }
    private String corePath,romPath,coreName;
    private static int screenMode=0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_main);
//        this.findView();
        Util.init(this);
        PACKAGE_NAME = getPackageName();
        romPath=getIntent().getStringExtra("romPath");
        corePath=getIntent().getStringExtra("corePath");
        coreName=getIntent().getStringExtra("coreName");
        screenMode=getIntent().getIntExtra("screenMode",0);


        checkCores();

    }
    private void checkCores(){
        if(TextUtils.isEmpty(corePath)){
            finish();
        }
        File file=new File(corePath);
        if(file.exists()){
            start();
        }else {
            startCopy(coreName,corePath);
        }
    }


    private void startCopy(final String fileName, final String toPath) {
        File file = new File(this.getFilesDir().getParent() + File.separator + "cores");
        if (!file.exists())
            file.mkdirs();
        new AsyncTask<String, Integer, String>() {
            @Override
            protected String doInBackground(String... strings) {
                copyFile(getFilesDir().getParent() + File.separator+"cores/" + fileName, fileName);
                return null;
            }

            @Override
            protected void onPostExecute(String s) {
                start();
                super.onPostExecute(s);
            }
        }.execute("");
    }


    private boolean copyFile(String file_path, String fileName) {
        File baseFile=new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/arcade/cores/");
        if(!baseFile.exists())//创建/arcade/cores文件夹
            baseFile.mkdirs();

        File file=new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/arcade/cores/"+fileName);
        if(!file.exists())//检测cores文件夹下是否存在.so
            return false;
        try {
            InputStream in = null;
//            in = this.getResources().getAssets().open("xucores/"+fileName);
            in= new FileInputStream(file);
            BufferedOutputStream outStream
                    = new BufferedOutputStream(new FileOutputStream(file_path, false));
            byte[] buffer = new byte[1024];
            int size;
            while ((size = in.read(buffer)) > 0) {
                outStream.write(buffer, 0, size);
            }
            in.close();
            outStream.flush();
            outStream.close();

            return true;

        } catch (IOException e) {
            e.printStackTrace();
        }

        return false;
    }
    private void start(){
        // Bind audio stream to hardware controls.
        setVolumeControlStream(AudioManager.STREAM_MUSIC);

        UserPreferences.updateConfigFile(this);

        checkRuntimePermissions();
    }

    private void findView() {
        this.mBtnLocalGame = findViewById(R.id.btn_start_local_game);
        this.mBtnNetP1 = findViewById(R.id.btn_start_net_game_p1);
        this.mBtnNetP2 = findViewById(R.id.btn_start_net_game_p2);
        this.mETRom = findViewById(R.id.et_rom);
        this.mETLib = findViewById(R.id.et_libs);
        this.mETConfig = findViewById(R.id.et_config);
        this.mBtnLocalGame.setOnClickListener(this);
        this.mBtnNetP1.setOnClickListener(this);
        this.mBtnNetP1.setOnClickListener(this);
    }


    @Override
    public void onClick(View view) {

        if (view == mBtnLocalGame) {

            if (!checkPermissions)
            {
            finalStartup();
            }

//            String PACKAGE_NAME = this.getPackageName();
//            Intent retro = new Intent(this, RetroArchEmulatorActivity.class);
//            retro.putExtra("ROM", "/storage/emulated/0/arcade/rom/kofxi.zip");
//            retro.putExtra("LIBRETRO", "/data/data/com.xugame.gameconsole/cores/flycast_libretro_android.so");
////            retro.putExtra("ROM", "");
////            retro.putExtra("LIBRETRO", "");
//
//            retro.putExtra("CONFIGFILE", "/storage/emulated/0/Android/data/com.xugame.gameconsole/files/retroarch.cfg");
//            retro.putExtra("IME", "com.android.inputmethod.latin/.LatinIME");
//            retro.putExtra("DATADIR", "/data/user/0/com.xugame.gameconsole");
//            retro.putExtra("APK", "/data/app/com.xugame.gameconsole-1/base.apk");
//            retro.putExtra("SDCARD", Environment.getExternalStorageDirectory().getAbsolutePath());
//            String external = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/" + PACKAGE_NAME + "/files";
//            retro.putExtra("EXTERNAL", external);
//            startActivity(retro);
        }

    }
}