package com.fusi24.rfid.ui;

import android.content.Intent;
import android.os.Bundle;
import android.widget.ToggleButton;

import com.fusi24.rfid.R;
import com.fusi24.rfid.ui.scanresult.ScanResultActivity;
import com.fusi24.rfid.util.LFScanProcessing;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnCheckedChanged;
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";

    @BindView(R.id.toggle_scan)
    ToggleButton toggleScan;

    private String idSite;
    private String idPermit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scan);
        ButterKnife.bind(this);
        initView();
        initSound();
    }

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

    @OnCheckedChanged(R.id.toggle_scan)
    public void statusScanner(){
        if(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);
    }

    @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);
                    }
                }
            }
        });
    }
}
