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 {

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

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

    @OnCheckedChanged(R.id.toggle_scan)
    public void statusScanner(){
        if(toggleScan.isChecked()){
            onStart();
        } else
            onStop();
    }

    void startInstance(String reception){
        Intent intent = new Intent(this, ScanResultActivity.class);
        intent.putExtra("reception", reception); //Optional parameters
        startActivityForResult(intent, 1);
    }

    @Override
    protected void onDataReceived(byte[] buffer, int size) {
        runOnUiThread(() -> {
            if (stringReception != 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);
                        stringReception = Integer.toString(temInt);

                        //Toast.makeText(ScanHomepage.this, "Hasil dari RFID LF: " + stringReception, Toast.LENGTH_LONG).show();
                        Timber.i("Hasil dari RFID LF: %s", stringReception);
                        startInstance(stringReception);
                    } else {
                        // receipt data 4 digit to start
                        stringReception = new String(buffer, 0, size);
                    }
                }
            }
        });
    }
}
