package com.fusi24.entryPermitScanner.ui.login;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import com.fusi24.entryPermitScanner.R;
import com.fusi24.entryPermitScanner.data.SessionManager;
import com.fusi24.entryPermitScanner.data.entity.DataAuth;
import com.fusi24.entryPermitScanner.data.entity.DataUser;
import com.fusi24.entryPermitScanner.databinding.ActivityLoginBinding;
import com.fusi24.entryPermitScanner.ui.setting.SettingActivity;
import com.fusi24.entryPermitScanner.util.Helper;
import com.fusi24.entryPermitScanner.util.LFScanProcessing;

import timber.log.Timber;

public class LoginActivity extends LFScanProcessing implements LoginView {

    private SessionManager session;
    private LoginPresenter presenter;
    private ActivityLoginBinding binding;

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

        presenter = new LoginPresenter(getManager(), getAndroidScheduler(), getProcessScheduler());
        presenter.attachView(this);
        session = new SessionManager(Helper.getDefaultPreferences(this));

        initEvent();
        initSound();
    }

    @Override
    protected void onResume() {
        super.onResume();
        onStart();
    }

    private void initEvent() {
        binding.ivIconScan.setOnClickListener(v -> {
            Intent intent = new Intent(this, SettingActivity.class);
            intent.putExtra(SettingActivity.IS_FROM_LOGIN, true);
            startActivity(intent);
        });
    }

    void startInstance(String numberRfidTemp){
        DataAuth dataAuth = new DataAuth();
        dataAuth.setRfidCode(Helper.formatRfidNumber(numberRfidTemp));
        presenter.userLogin(dataAuth);
    }

    // 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
    public void showLoginSuccess(DataUser dataUser) {
        if (dataUser.isSuccess()){
            session.setUserLogin();
            session.setUserId(Integer.valueOf(dataUser.getIdKaryawan()));
            session.setUserName(dataUser.getUsername());
            session.setEmployeeName(dataUser.getNamaKaryawan());
            session.setUserSid(dataUser.getKodeKaryawan());
            session.setUserEmail(dataUser.getEmail());
            session.setUserTelephone(dataUser.getSelular());
            session.setUserRfidNumber(Helper.formatRfidNumber(rfidCardNumber));

            Intent result = new Intent();
            setResult(Activity.RESULT_OK, result);
            finish();
        } else {
            Toast.makeText(this, getString(R.string.error_only_security), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        Intent startMain = new Intent(Intent.ACTION_MAIN);
        startMain.addCategory(Intent.CATEGORY_HOME);
        startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(startMain);
    }

    @Override
    public void showError(Throwable e) {
        Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
    }

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