package com.fusi24.rfid.ui;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;

import com.fusi24.rfid.R;
import com.fusi24.rfid.config.Constant;
import com.fusi24.rfid.databinding.ActivityScanBinding;
import com.fusi24.rfid.ui.scanresult.ScanResultActivity;
import com.fusi24.rfid.util.LFScanProcessing;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;

import timber.log.Timber;

public class ScanActivity extends LFScanProcessing {

    public static final String ID_PERMIT = "id_permit";
    public static final String ID_DEVICE = "id_device";
    public static final String ID_CHECK_TYPE = "id_check_type";
    public static final String CHECK_TYPE_NAME = "check_type_name";

    private String idPermit, idDevice, idCheckType, checkTypeName, longLat;
    private ActivityScanBinding binding;
    private FusedLocationProviderClient locationClient;

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

        Toolbar toolbar = findViewById(R.id.toolbar);
        TextView toolbarTitle = findViewById(R.id.toolbar_text);

        if(toolbarTitle !=null && toolbar !=null) {
            toolbarTitle.setText(getString(R.string.app_name));
            setSupportActionBar(toolbar);
        }

        if (getSupportActionBar() != null){
            getSupportActionBar().setDisplayShowTitleEnabled(false);
        }

        initView();
        initSound();
    }

    private void initView() {
        if (getIntent().getExtras() != null){
            idPermit = getIntent().getExtras().getString(ID_PERMIT);
            idDevice = getIntent().getExtras().getString(ID_DEVICE);
            idCheckType = String.valueOf(getIntent().getExtras().getInt(ID_CHECK_TYPE));
            checkTypeName = getIntent().getExtras().getString(CHECK_TYPE_NAME);
        }

        setStatusScan();
        locationClient = LocationServices.getFusedLocationProviderClient(this);
        getLocation();
        binding.toggleScan.setOnCheckedChangeListener((buttonView, isChecked) -> statusScanner());
    }

    private void setStatusScan(){
        switch (Integer.parseInt(idCheckType)){
            case 649 :
                binding.tvStatusScan.setBackground(getDrawable(R.drawable.bg_green));
                break;
            case 650 :
            default:
                binding.tvStatusScan.setBackground(getDrawable(R.drawable.bg_blue));
                break;
        }
        binding.tvStatusScan.setText(checkTypeName);
    }

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

    void startInstance(String rfidCardNumber){
        Intent intent = new Intent(this, ScanResultActivity.class);
        intent.putExtra(ScanResultActivity.RFID_CARD_NUMBER, rfidCardNumber);
        intent.putExtra(ScanResultActivity.ID_PERMIT, idPermit);
        intent.putExtra(ScanResultActivity.ID_DEVICE, idDevice);
        intent.putExtra(ScanResultActivity.ID_CHECK_TYPE, idCheckType);
        intent.putExtra(ScanResultActivity.CHECK_TYPE_NAME, checkTypeName);
        intent.putExtra(ScanResultActivity.LOCATION, longLat);
        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);
                    }
                }
            }
        });
    }

    private void getLocation() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, Constant.PERMISSIONS_RFID, 1000);
            return;
        }
        locationClient.getLastLocation().addOnSuccessListener(this, location -> {
            if (location != null){
                double latitude = location.getLatitude();
                double longitude = location.getLongitude();
                longLat = longitude + "," + latitude;
                Timber.d("DEVELOPER Location : " + location.getLatitude() + " , " + location.getLongitude());
            }
        });
    }

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