package com.fusi24.rfid.ui.home;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.fusi24.rfid.BuildConfig;
import com.fusi24.rfid.R;
import com.fusi24.rfid.SplashScreenActivity;
import com.fusi24.rfid.adapter.SiteAdapter;
import com.fusi24.rfid.adapter.StatusScanAdapter;
import com.fusi24.rfid.base.BaseActivity;
import com.fusi24.rfid.config.Constant;
import com.fusi24.rfid.data.entity.DataDetail;
import com.fusi24.rfid.data.entity.DataDevice;
import com.fusi24.rfid.data.entity.DataEntryPermit;
import com.fusi24.rfid.databinding.ActivityHomeBinding;
import com.fusi24.rfid.ui.ScanActivity;

import java.util.ArrayList;
import java.util.List;

import timber.log.Timber;

public class HomeActivity extends BaseActivity implements HomeView, StatusScanAdapter.OnItemSelected {

    private DataEntryPermit dataEntryPermit;
    private List<DataEntryPermit> entryPermitList;
    private List<DataDetail> statusScanList;
    private ActivityHomeBinding binding;
    private HomePresenter presenter;
    private StatusScanAdapter scanAdapter;
    private SiteAdapter siteAdapter;
    private Integer idCheckType = null;
    private String idDevice, checkTypeName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityHomeBinding.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);
        }

        presenter = new HomePresenter(getManager(), getAndroidScheduler(), getProcessScheduler());
        presenter.attachView(this);

        initView();
        loadingData();
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        menu.findItem(R.id.app_version)
                .setEnabled(false)
                .setTitle(BuildConfig.VERSION_NAME);
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_home, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {

        if (item.getItemId() == R.id.action_logout) {
            getSessionManager().clearData();
            startActivity(new Intent(this, SplashScreenActivity.class));
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

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

    private void initView(){
        binding.refresh.setRefreshing(false);
        ActivityCompat.requestPermissions(this, Constant.PERMISSIONS_RFID, 1000);

        entryPermitList = new ArrayList<>();
        statusScanList = new ArrayList<>();

        scanAdapter = new StatusScanAdapter(this, this);
        binding.rvStatusScan.setLayoutManager(new LinearLayoutManager(this));
        binding.rvStatusScan.setItemAnimator(new DefaultItemAnimator());
        binding.rvStatusScan.setAdapter(scanAdapter);

        siteAdapter = new SiteAdapter(this);
        binding.rvSite.setLayoutManager(new LinearLayoutManager(this));
        binding.rvSite.setItemAnimator(new DefaultItemAnimator());
        binding.rvSite.setAdapter(siteAdapter);
    }

    @SuppressLint("SetTextI18n")
    private void loadingData(){
        idDevice = "RFID-" + Build.ID + "-" + Build.DEVICE;
        binding.tvRfidGunId.setText(idDevice);
        binding.tvRfidCardNumber.setText(getSessionManager().getUserRfidNumber());
        binding.tvEmployeeName.setText(getSessionManager().getEmployeeName());

        presenter.getEntryPermit();
        presenter.getStatusScan();
        presenter.getDataDevice(idDevice);
    }

    private void initEvent(){

        binding.spinnerPermit.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                dataEntryPermit = (DataEntryPermit) parent.getItemAtPosition(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                dataEntryPermit = (DataEntryPermit) parent.getSelectedItem();
            }
        });

        binding.btnScan.setOnClickListener(v -> {

            if (binding.spinnerPermit.getSelectedItem() == null){
                Toast.makeText(this, "Data Permit Belum Terpilih", Toast.LENGTH_SHORT).show();
                return;
            }

            if (idCheckType == null){
                Toast.makeText(this, "Status Scan Belum Terpilih", Toast.LENGTH_SHORT).show();
                return;
            }

            Intent intent = new Intent(this, ScanActivity.class);
            intent.putExtra(ScanActivity.ID_PERMIT, String.valueOf(dataEntryPermit.getId()));
            intent.putExtra(ScanActivity.ID_DEVICE, idDevice);
            intent.putExtra(ScanActivity.ID_CHECK_TYPE, idCheckType);
            intent.putExtra(ScanActivity.CHECK_TYPE_NAME, checkTypeName);
            startActivity(intent);
        });

        binding.refresh.setOnRefreshListener(this::loadingData);

    }

    @Override
    public void onSelected(DataDetail detail) {
        idCheckType = detail.getId();
        checkTypeName = detail.getName();
    }

    @Override
    public void showDataPermit(List<DataEntryPermit> dataEntryPermitList) {
        entryPermitList.clear();
        entryPermitList.addAll(dataEntryPermitList);
        setDataPermit();
    }

    @Override
    public void showDataStatusScan(List<DataDetail> dataStatusScanList) {
        binding.refresh.setRefreshing(false);
        statusScanList.clear();
        statusScanList.addAll(dataStatusScanList);
        scanAdapter.updateDetailList(statusScanList);
        scanAdapter.notifyDataSetChanged();
    }

    @Override
    public void showDataDevice(List<DataDevice> dataDevices) {
        binding.tvGateName.setText(dataDevices.get(0).getGate().getName());
        siteAdapter.updateSiteList(dataDevices.get(0).getGate().getSites());
        siteAdapter.notifyDataSetChanged();
    }

    private void setDataPermit(){
        ArrayAdapter<DataEntryPermit> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, entryPermitList);
        binding.spinnerPermit.setAdapter(adapter);
    }

    @Override
    public void showError(Throwable e) {
        binding.refresh.setRefreshing(false);
        Toast.makeText(HomeActivity.this, "Failed get data, try refresh again", Toast.LENGTH_SHORT).show();
        Timber.i("DEVELOPER : %s", e.getMessage());
    }

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