package com.fusi24.rfid.ui;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import com.fusi24.rfid.databinding.ActivityScanBinding;
import com.fusi24.rfid.ui.scanresult.ScanResultActivity;
import com.fusi24.rfid.util.LFScanProcessing;

import timber.log.Timber;

public class ScanActivity extends LFScanProcessing {

    public static final String ID_SITE = "id_site";
    public static final String ID_PERMIT = "id_permit";

    private String idSite;
    private String idPermit;
    private ActivityScanBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityScanBinding.inflate(getLayoutInflater());
        View view = binding.getRoot();
        setContentView(view);
        initView();
        initSound();
    }

    private void initView() {
        if (getIntent().getExtras() != null){
            idSite = getIntent().getExtras().getString(ID_SITE);
            idPermit = getIntent().getExtras().getString(ID_PERMIT);
        }

        binding.toggleScan.setOnCheckedChangeListener((buttonView, isChecked) -> statusScanner());
    }

    public void statusScanner(){
        if(binding.toggleScan.isChecked()){
            onStart();
        } else
            onStop();
    }

    void startInstance(String rfidCardNumber){
        Intent intent = new Intent(this, ScanResultActivity.class);
        intent.putExtra(ScanResultActivity.ID_SITE, idSite);
        intent.putExtra(ScanResultActivity.ID_PERMIT, idPermit);
        intent.putExtra(ScanResultActivity.RFID_CARD_NUMBER, rfidCardNumber);
        startActivityForResult(intent, 1);
    }

    // This method for read chip number in the card
    @Override
    protected void onDataReceived(byte[] buffer, int size) {
        runOnUiThread(() -> {
            if (rfidCardNumber != null) {
                if (size > 0) {
                    if (size >= 5) {
                        byte[] tempBuf = new byte[size - 4];
                        System.arraycopy(buffer, 4, tempBuf, 0, size - 4);//discard 4 bit
                        String temStr = new String(tempBuf);
                        int temInt = Integer.parseInt(temStr, 16);
                        soundpool.play(soundid, 1, 1, 0, 0, 1);
                        rfidCardNumber = Integer.toString(temInt);

                        Timber.i("Hasil dari RFID LF: %s", rfidCardNumber);
                        startInstance(rfidCardNumber);
                    } else {
                        // receipt data 4 digit to start
                        rfidCardNumber = new String(buffer, 0, size);
                    }
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        binding = null;
    }
}
