package com.xugame.gameconsole;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.xugame.gameconsole.emulator.EmulatorType;
import com.xugame.gameconsole.util.AssetsUtils;
import com.xugame.gameconsole.util.DebugUtil;
import com.xugame.gameconsole.util.PermissionsUtils;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class TextCopyFileActivity extends Activity {
    private static final String TAG = "TextCopyFileActivityTAG";
    private Button btn1, btn2, btn3, btn4;
    private Context mContext;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        DebugUtil.i("EMULATORTAG","Copy ac onCreate");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.textcopp_layout);
        this.mContext = this;
        String[] permissions = new String[]{
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.CHANGE_NETWORK_STATE,
                Manifest.permission.CHANGE_WIFI_STATE,
                Manifest.permission.RECORD_AUDIO,
                Manifest.permission.MODIFY_AUDIO_SETTINGS,
                Manifest.permission.WAKE_LOCK
        };
//        PermissionsUtils.showSystemSetting = false;//是否支持显示系统设置权限设置窗口跳转
        //这里的this不是上下文，是Activity对象！
        PermissionsUtils.getInstance().chekPermissions(this, permissions, permissionsResult);

        init();
        DebugUtil.i(TAG,""+this.getFilesDir().getParent()+"/assets");
    }

    @Override
    protected void onResume() {
        DebugUtil.i("EMULATORTAG","Copy ac onResume");
        super.onResume();
    }

    @Override
    protected void onPause() {
        DebugUtil.i("EMULATORTAG","Copy ac onPause");
        super.onPause();
    }

    @Override
    protected void onStop() {
        DebugUtil.i("EMULATORTAG","Copy ac onStop");
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        DebugUtil.i("EMULATORTAG","Copy ac onDestroy");
        super.onDestroy();
    }

    @Override
    protected void onRestart() {
        DebugUtil.i("EMULATORTAG","Copy ac onRestart");
        super.onRestart();
    }

    //创建监听权限的接口对象
    PermissionsUtils.IPermissionsResult permissionsResult = new PermissionsUtils.IPermissionsResult() {
        @Override
        public void passPermissons() {

//            Toast.makeText(MainActivity.this, "权限通过，可以做其他事情!", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void forbitPermissons() {
//            finish();
            Toast.makeText(mContext, "Failed to obtain permissions!", Toast.LENGTH_SHORT).show();
        }
    };

    private void init() {
        btn1 = findViewById(R.id.btn1);
        btn2 = findViewById(R.id.btn2);
        btn3 = findViewById(R.id.btn3);
        btn4 = findViewById(R.id.btn4);
        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ///cores/fbalpha2012_neogeo_libretro_android.so
                startGame(Environment.getExternalStorageDirectory().getAbsolutePath() + "/arcade/rom/kof97.zip",
                        mContext.getFilesDir().getParent() + "/cores/fbalpha2012_neogeo_libretro_android.so",
                        EmulatorType.NEOGEO);
            }
        });
        btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startGame(Environment.getExternalStorageDirectory().getAbsolutePath() + "/arcade/rom/gigawing.zip",
                        mContext.getFilesDir().getParent() + "/cores/fbalpha2012_cps2_libretro_android.so",
                        EmulatorType.CPS2);

            }
        });
        btn3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startGame(Environment.getExternalStorageDirectory().getAbsolutePath() + "/arcade/rom/super_mario_bros_world.nes",
                        mContext.getFilesDir().getParent() + "/cores/mesen_libretro_android.so",
                        EmulatorType.NES);

            }
        });
        btn4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startGame(Environment.getExternalStorageDirectory().getAbsolutePath() + "/arcade/rom/PPSSPP/三国无双/三国无双.iso",
                        mContext.getFilesDir().getParent() + "/cores/ppsspp_libretro_android.so",
                        EmulatorType.PSP);
            }
        });
    }

    private void startGame(String rompath, String corepath, EmulatorType Type) {
        File file = new File(corepath);
        if (file.exists()) {
            Intent intent = new Intent(this, MainActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.putExtra("romPath", rompath);
            intent.putExtra("corePath", corepath);
            startActivity(intent);
        } else {
            DebugUtil.i(TAG, "core 不存在");
            String coreName = "";
            switch (Type) {
                case CPS2:
                    coreName = "fbalpha2012_cps2_libretro_android.so";
                    break;
                case NEOGEO:
                    coreName = "fbalpha2012_neogeo_libretro_android.so";
                    break;
                case NES:
                    coreName = "mesen_libretro_android.so";
                    break;
                case PSP:
                    coreName = "ppsspp_libretro_android.so";
                    break;
            }
            if (!TextUtils.isEmpty(coreName))
                startCopy(coreName,
                        "/data/user/0/" + getPackageName() + "/cores/");

        }
    }

    private void showDialog(final String fileName, final String toPath) {
        AlertDialog.Builder alertDialog = new ProgressDialog.Builder(this)
                .setTitle("Yes/No")
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        startCopy(fileName, toPath);
                        dialog.dismiss();
                    }
                })
                .setNegativeButton("No", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setMessage("是否复制" + fileName);
        alertDialog.show();
    }

    private void startCopy(final String fileName, final String toPath) {
        File file = new File(this.getFilesDir().getParent() + File.separator + "cores");
        if (!file.exists())
            file.mkdirs();
        Log.i(TAG, "file=" + file.getPath());
        showProgress();
        new AsyncTask<String, Integer, String>() {
            @Override
            protected String doInBackground(String... strings) {
                copyFile("/data/user/0/com.xugame.gameconsole/cores/" + fileName, fileName);
                return null;
            }

            @Override
            protected void onPostExecute(String s) {
                Log.i(TAG, "onPostExecute");
                if(mProgressDialog!=null)
                    mProgressDialog.dismiss();
                Toast.makeText(mContext, "核心安装完成", Toast.LENGTH_SHORT).show();
                super.onPostExecute(s);
            }
        }.execute("");
    }

    private boolean copyFile(String file_path, String fileName) {
        Log.i(TAG, "copyFile" + "filepath=" + file_path+"filename="+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;
        Log.i(TAG,"");
        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;
    }

    ProgressDialog mProgressDialog;

    private void showProgress() {
        mProgressDialog = ProgressDialog.show(this, "核心安装",
                "正在安装核心。。。");
        mProgressDialog.show();
    }

    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        DebugUtil.i(TAG,"onConfigurationChanged"+newConfig.toString());
        super.onConfigurationChanged(newConfig);
    }

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

    @Override
    protected void onNewIntent(Intent intent) {
        DebugUtil.i(TAG,"onNewIntent");
        super.onNewIntent(intent);
    }

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

    @Override
    public void onWindowAttributesChanged(WindowManager.LayoutParams params) {
        DebugUtil.i(TAG,"onWindowAttributesChanged");
        super.onWindowAttributesChanged(params);
    }

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

}
