package com.example.tyre;


import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.android.hdhe.uhf.reader.UhfReader;
import com.android.hdhe.uhf.readerInterface.TagModel;
import com.example.tyre.entity.BaseTyre;
import com.example.tyre.entity.EPC;
import com.example.tyre.entity.Tyre;
import com.example.tyre.util.CommonDialog;
import com.example.tyre.util.MyUrl;
import com.example.tyre.util.PlayMusic;
import com.example.tyre.util.Util;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import androidx.appcompat.app.AppCompatActivity;
import cn.pda.serialport.Tools;
import com.example.tyre.databinding.ActivityTyresearchBinding;


public class TyreSearchActivity extends AppCompatActivity {
    private ActivityTyresearchBinding binding;

    TextView inSantext;
    Button basemessage;
    Button button;
    TextView pinpai;
    TextView xinghao;
    TextView cengji;
    TextView huawen;
    private int power = 0;
    private int area = 0;
    private SharedPreferences shared;
    private TextView textVersion;

    private boolean runFlag = true;
    private boolean startFlag = false;
    private UhfReader manager;
    private ArrayList<EPC> listEPC;
    private ArrayList<String> listepc = new ArrayList<String>();
    private ProgressDialog progressDialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityTyresearchBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        bindViews();
        setupClickListeners();
        manager = MyApplication.getManager();
        initView();
        Thread thread = new InventoryThread();
        thread.start();
        com.example.tyre.util.Util.initSoundPool(this);
        Log.e("onCreate", "onCreate:+ " );
    }

    private void bindViews() {
        inSantext = binding.inSantext;
        basemessage = binding.basemessage;
        button = binding.button;
        pinpai = binding.pinpai;
        xinghao = binding.xinghao;
        cengji = binding.cengji;
        huawen = binding.huawen;
    }

    private void setupClickListeners() {
        binding.scanButton.setOnClickListener(v -> {
            if (!startFlag) {
                startFlag = true;
                binding.scanButton.setText("停     止");
            } else {
                startFlag = false;
                binding.scanButton.setText("扫     描");
            }
        });
        binding.button.setOnClickListener(v -> {
            // Intent intent = new Intent(this, HomePageActivity.class);
            // startActivity(intent);
            finish();
        });
    }



    @Override
    public void onResume() {
        super.onResume();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        registerReceiver();
    }


    @Override
    public void onPause() {
        startFlag = false;
        binding.scanButton.setText("扫描");
       // manager.close();
        unregisterReceiver();
        Log.e("onPause", "onPause:+ " );
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        startFlag = false;
        runFlag = false;
        Log.e("onDestroy", "onDestroy:+ " );
        super.onDestroy();
    }

    private void initView() {
        textVersion = binding.inSantext;
        pinpai = binding.pinpai;
        xinghao = binding.xinghao;
        cengji = binding.cengji;
        huawen = binding.huawen;

        listEPC = new ArrayList<EPC>();
    }
    private long exitTime = 0;

    private Toast mToast;


    private Toast toast;

    class InventoryThread extends Thread {
        private List<TagModel> tagList;
        byte[] accessPassword = Tools.HexString2Bytes("00000000");
        @Override
        public void run() {
            super.run();
            while (runFlag) {
                if (startFlag) {
                    tagList = manager.inventoryRealTime();
                    if (tagList != null && !tagList.isEmpty()) {
                        Util.play(1, 0);
                        for (TagModel tag : tagList) {
                            if (tag == null) {
                                String epcStr = "";
                                addToList(listEPC, epcStr, (byte) -1);
                            } else {
                                String epcStr = Tools.Bytes2HexString(tag.getmEpcBytes(), tag.getmEpcBytes().length);
                                byte rssi = tag.getmRssi();
                                addToList(listEPC, epcStr, rssi);
                            }

                        }
                    }
                    tagList = null;
                    try {
                        Thread.sleep(20);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    private void addToList(final List<EPC> list, final String epc, final byte rssi) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (list.isEmpty()) {
                    EPC epcTag = new EPC();
                    epcTag.setEpc(epc);
                    epcTag.setCount(1);
                    epcTag.setRssi(rssi);
                    list.add(epcTag);
                    listepc.add(epc);

                }else {
                    for (int i = 0; i < list.size(); i++) {
                        EPC mEPC = list.get(i);
                        if (epc.equals(mEPC.getEpc())) {
                            mEPC.setCount(mEPC.getCount() + 1);
                            mEPC.setRssi(rssi);
                            list.set(i, mEPC);
                            break;
                        } else if (i == (list.size() - 1)) {
                            EPC newEPC = new EPC();
                            newEPC.setEpc(epc);
                            newEPC.setCount(1);
                            newEPC.setRssi(rssi);
                            list.add(newEPC);
                            listepc.add(epc);
                        }
                    }
                }

                lastTime =  SystemClock.elapsedRealtime();
                long time = lastTime - nextTime;
                if (time >= 60) {
                    Util.play(1, 0);
                    nextTime = lastTime;
                    Log.e("TAG", "run: " + time);
                }
            }
        });
        Log.e("EPC", "listepc:+ " + listepc);
        if (listepc != null && !listepc.isEmpty()){
            startFlag = false;
            binding.scanButton.setText("扫     描");
            textVersion.setText(listepc.get(0).toString());
            find(listepc.get(0).toString());
        }
        clearData();
    }
    long lastTime;
    long nextTime;
    private void setButtonClickable(Button button, boolean flag) {
        button.setClickable(flag);
        if (flag) {
            button.setTextColor(Color.BLACK);
        } else {
            button.setTextColor(Color.GRAY);
        }
    }


    private void showToast(String message) {
        if (mToast == null) {
            mToast = Toast.makeText(TyreSearchActivity.this, message, Toast.LENGTH_SHORT);
            mToast.show();
        } else {
            mToast.setText(message);
            mToast.show();
        }
    }
    private void clearData() {
        listEPC.removeAll(listEPC);
        listepc.removeAll(listepc);
    }

    private KeyReceiver keyReceiver;
    private void registerReceiver() {
        keyReceiver = new KeyReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.rfid.FUN_KEY");
        filter.addAction("android.intent.action.FUN_KEY");
        registerReceiver(keyReceiver, filter);
    }

    private void unregisterReceiver() {
        unregisterReceiver(keyReceiver);
    }

    private class KeyReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            int keyCode = intent.getIntExtra("keyCode", 0);
            if (keyCode == 0) {
                keyCode = intent.getIntExtra("keycode", 0);
            }
            boolean keyDown = intent.getBooleanExtra("keydown", false);
            if (keyDown) {
                if (toast == null) {
                } else {
                }
                switch (keyCode) {
                    case KeyEvent.KEYCODE_F1:
                    case KeyEvent.KEYCODE_F2:
                    case KeyEvent.KEYCODE_F3:
                    case KeyEvent.KEYCODE_F4:
                    case KeyEvent.KEYCODE_F5:
                    case 136:
                       binding.scanButton.callOnClick();
                        break;
                }
            }
        }
    }
    private void find(String epc) {
        OkGo.<String>post(MyUrl.url + "/tyre/tyre/pdaQueryTyreInfo").tag(this)
                .params("tyreEpc", epc)
                .execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                String body = response.body();
                try {
                    Gson gson = new Gson();
                    BaseTyre baseTyre = gson.fromJson(body, BaseTyre.class);
                    if (baseTyre != null) {
                        String brand = safeGetString(baseTyre.getTyreBrand());
                        String model = safeGetString(baseTyre.getTyreModel());
                        String level = safeGetString(baseTyre.getTyreLevel());
                        String pattern = safeGetString(baseTyre.getTyrePattern());

                        pinpai.setText(brand);
                        xinghao.setText(model);
                        cengji.setText(level);
                        huawen.setText(pattern);
                    }else {
                        pinpai.setText("");
                        xinghao.setText("");
                        cengji.setText("");
                        huawen.setText("");
                    }
                } catch (JsonSyntaxException e) {
                    pinpai.setText("");
                    xinghao.setText("");
                    cengji.setText("");
                    huawen.setText("");
                    return;
                }
            }
        });
    }
    private String safeGetString(String value) {
        return value == null || "null".equals(value) ? "" : value;
    }
}
