package com.zzliaoyuan.power_sensor;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.media.AudioManager;
import android.media.SoundPool;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.view.KeyEvent;
import android.widget.Toast;

import com.facebook.react.ReactActivity;

import androidx.annotation.NonNull;
import com.github.dfqin.grantor.PermissionListener;
import com.github.dfqin.grantor.PermissionsUtil;
import com.rscja.deviceapi.RFIDWithUHFUART;
import com.swmansion.gesturehandler.react.RNGestureHandlerEnabledRootView;
import com.zzliaoyuan.power_sensor.fragment.UHFReadTagFragment;
import com.zzliaoyuan.rifdmastercore.LibCore;

import java.io.FileInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;


import com.facebook.react.ReactActivity;
import com.facebook.react.ReactActivityDelegate;
import com.facebook.react.ReactRootView;
import com.swmansion.gesturehandler.react.RNGestureHandlerEnabledRootView;

import java.io.FileInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;

import com.zzliaoyuan.power_sensor.MainApplication;
import com.zzliaoyuan.power_sensor.R;
import com.rscja.deviceapi.RFIDWithUHFUART;
import com.zzliaoyuan.power_sensor.fragment.UHFReadTagFragment;
import com.zzliaoyuan.rifdmastercore.LibCore;

public class MainActivity extends ReactActivity {

    /**
     * Returns the name of the main component registered from JavaScript. This is used to schedule
     * rendering of the component.
     */
    @Override
    protected String getMainComponentName() {
        return "power_sensor";
    }

    public RFIDWithUHFUART mReader;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(null);
        requirePerms();
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); // 禁用横屏

//        verifyStoragePermissions(this);
        checkLicense();
    }

    private void requirePerms() {
//        String[] permissions = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};

        String[] mPermissionList = new String[]{
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
        };
        if (!PermissionsUtil.hasPermission(this, mPermissionList)) {
            PermissionsUtil.requestPermission(this, new PermissionListener() {
                @Override
                public void permissionGranted(@NonNull String[] mPermissionList) {
                    //用户授予了权限

                }

                @Override
                public void permissionDenied(@NonNull String[] mPermissionList) {
                    //用户拒绝了申请
                    Toast.makeText(MainActivity.this, "您拒绝了相关的权限，将无法使用部分功能！", Toast.LENGTH_SHORT).show();
                }
            }, mPermissionList);
        }
    }


//    @Override
//    protected ReactActivityDelegate createReactActivityDelegate() {
//        return new ReactActivityDelegate(this, getMainComponentName()) {
//            @Override
//            protected ReactRootView createRootView() {
//                return new RNGestureHandlerEnabledRootView(MainActivity.this);
//            }
//        };
//    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == 139 || keyCode == 280 || keyCode == 293) {

            if (event.getRepeatCount() == 0) {
                UHFReadTagFragment.getInstance().myOnKeyDwon();
                MainApplication.GetReactPackage().reactModule.sendMsgToRN("onKeyDown", "1");
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    public void checkLicense() {
        // 生成机器码
        String macCode = null;
        String serialNumber = "ZZLY_" + Build.SERIAL;
        MessageDigest md = null;
        byte[] bt = serialNumber.getBytes();
        try {
            md = MessageDigest.getInstance("SHA-256");
            md.update(bt);
            macCode = bytes2Hex(md.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        // 读取授权文件
        StringBuilder sb = new StringBuilder("");
        try {
            String filename = Environment.getExternalStorageDirectory().getCanonicalPath() + "/rfidmaster.lic";
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                FileInputStream input = new FileInputStream(filename);
                byte[] temp = new byte[1024];

                int len = 0;
                while ((len = input.read(temp)) > 0) {
                    sb.append(new String(temp, 0, len));
                }
                input.close();
            }

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

        String licenseCode = sb.toString().trim();
        boolean ret = LibCore.verifyLicense(macCode, licenseCode);
        if (ret) {
            initSound();
            initUHF();
            UHFReadTagFragment.getInstance().setContext(this);
            UHFReadTagFragment.getInstance().setUserModel();
        } else {
            final AlertDialog.Builder normalDialog = new AlertDialog.Builder(this);
//            normalDialog.setTitle("电金晴");
            normalDialog.setMessage("掌机认证失败，请联系供应商!\n macCode："+macCode+"。licenseCode:"+licenseCode);
            normalDialog.setPositiveButton("确定",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            System.exit(0);
                        }
                    });

            normalDialog.show();
        }

    }

    /**
     * byte数组转换为16进制字符串
     *
     * @param bts 数据源
     * @return 16进制字符串
     */
    public static String bytes2Hex(byte[] bts) {
        String des = "";
        String tmp = null;
        for (int i = 0; i < bts.length; i++) {
            tmp = (Integer.toHexString(bts[i] & 0xFF));
            if (tmp.length() == 1) {
                des += "0";
            }
            des += tmp;
        }
        return des;
    }

    // 初始化声音
    HashMap<Integer, Integer> soundMap = new HashMap<Integer, Integer>();
    private SoundPool soundPool;
    private float volumnRatio;
    private AudioManager am;

    private void initSound() {
        soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 5);
        soundMap.put(1, soundPool.load(this, R.raw.barcodebeep, 1));
        soundMap.put(2, soundPool.load(this, R.raw.serror, 1));
        am = (AudioManager) this.getSystemService(AUDIO_SERVICE);// 实例化AudioManager对象
    }

    /**
     * 播放提示音
     *
     * @param id 成功1，失败2
     */
    public void playSound(int id) {
        float audioMaxVolumn = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC); // 返回当前AudioManager对象的最大音量值
        float audioCurrentVolumn = am.getStreamVolume(AudioManager.STREAM_MUSIC);// 返回当前AudioManager对象的音量值
        volumnRatio = audioCurrentVolumn / audioMaxVolumn;
        try {
            soundPool.play(soundMap.get(id), volumnRatio, // 左声道音量
                    volumnRatio, // 右声道音量
                    1, // 优先级，0为最低
                    0, // 循环次数，0无不循环，-1无永远循环
                    1 // 回放速度 ，该值在0.5-2.0之间，1为正常速度
            );
        } catch (Exception e) {
            e.printStackTrace();

        }
    }

    public void initUHF() {

        try {
            mReader = RFIDWithUHFUART.getInstance();
            toastMessage("初始化读卡器");
        } catch (Exception ex) {
//            Log.e("======", ex.getMessage());
            toastMessage(ex.getMessage());

            return;
        }

        if (mReader != null) {
            mReader.init();
        }
    }

    public void toastMessage(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onDestroy() {
        Uri data = Uri.parse("file:///storage/emulated/0/assetsLog/assets.txt");
        this.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, data));
        if (mReader != null) {
            mReader.free();
        }
        super.onDestroy();
    }
}
