package com.example.writeepc;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.databinding.DataBindingUtil;

import com.example.writeepc.base.BaseActivity;
import com.example.writeepc.databinding.ActivityKillBinding;
import com.uhf.api.cls.Reader;

import cn.pda.serialport.Tools;

public class KillActivity extends BaseActivity {
    private TextView opEpc;
    private byte[] readTid;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityKillBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_kill);
        opEpc = binding.opEpc;
        initUHFRManager();
    }

    public void readRFID(View view) {
        readTid();
    }

    @Override
    protected void readTidReault(boolean readState, String result, byte[] rdata) {
        super.readTidReault(readState, result, rdata);
        opEpc.setText(result);
        readTid = rdata;
    }

    public void killRFID(View view) {
        if (readTid == null) return;
        Log.e("TAG", "killRFID:" + "开始查询...");
        byte[] rdata = uhfrManager.getTagDataByFilter(0, 0, 2, accesspwd, timeOut, readTid, 2, 0, true);
        if (rdata != null) {
            String pass = Tools.Bytes2HexString(rdata, rdata.length);
            Log.e("TAG", "查询成功，密码:" + pass);

            if (pass.equals("00000000")) {
                // Toast.makeText(this, "全0密码不能灭活标签", Toast.LENGTH_LONG).show();
                writePass();
                return;
            }
            rfIDKill(rdata);
        } else {
            Toast.makeText(this, "密码查询失败", Toast.LENGTH_LONG).show();
        }
    }

    private void writePass() {
        Log.e("TAG", "writePass:" + "开始写密码...");
        byte[] pass=Tools.HexString2Bytes("00000008");
        int length = pass.length;
        Log.e("TAG", "write length:" + length);
        Reader.READER_ERR readerErr = uhfrManager.writeTagDataByFilter((char) 0, 0
                , pass, pass.length, accesspwd, timeOut, readTid, 2, 0, true);
        Log.e("TAG", "写密码 LOG:" +readerErr.toString());
       if (readerErr== Reader.READER_ERR.MT_OK_ERR) {
           Log.e("TAG", "写密码:" +"ok");
           rfIDKill(pass);
           return;
       }

        Log.e("TAG", "写密码:" +"no");

    }


    private void rfIDKill(byte[] rdata){
        Log.e("TAG", "rfIDKill:" + "开始灭活...");
        // Reader.READER_ERR readerErr = uhfrManager.killTagByFilter(rdata,timeOut, readTid, 2, 0, true);
        Reader.READER_ERR readerErr = uhfrManager.killTag(rdata,timeOut);
        if (readerErr == Reader.READER_ERR.MT_OK_ERR) {
            music.start();
            Toast.makeText(this, "成功", Toast.LENGTH_SHORT).show();
            opEpc.setText(null);
            readTid = null;
            return;
        }
        Toast.makeText(this, "Kill ERROR LOG：" + readerErr.toString(), Toast.LENGTH_SHORT).show();
    }

}