package com.fusi24.rfid.ui.scanresult;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.annimon.stream.Collectors;
import com.annimon.stream.Stream;
import com.bumptech.glide.Glide;
import com.fusi24.rfid.R;
import com.fusi24.rfid.adapter.ProblemGroupAdapter;
import com.fusi24.rfid.base.BaseActivity;
import com.fusi24.rfid.config.Constant;
import com.fusi24.rfid.data.entity.DataGroup;
import com.fusi24.rfid.data.entity.DataProblems;
import com.fusi24.rfid.data.entity.DataResultRfid;
import com.fusi24.rfid.databinding.ActivityScanResultNewBinding;
import com.fusi24.rfid.ui.home.HomeActivity;

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

public class ScanResultActivity extends BaseActivity implements ScanResultView {

    public static final String RFID_CARD_NUMBER = "rfid_card_number";
    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";
    public static final String LOCATION = "location";

    private ScanResultPresenter presenter;
    private ProblemGroupAdapter adapter;
    private List<DataProblems> problemsList;
    private String dataUrl, numberRfid, numberRfidTemp, idPermit, idDevice, idCheckType, checkTypeName, longLat;
    private ActivityScanResultNewBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityScanResultNewBinding.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 ScanResultPresenter(
                getManager(), getAndroidScheduler(), getProcessScheduler());
        presenter.attachView(this);

        if (getIntent() != null) {
            numberRfidTemp = getIntent().getStringExtra(RFID_CARD_NUMBER);
            idPermit = getIntent().getStringExtra(ID_PERMIT);
            idDevice = getIntent().getStringExtra(ID_DEVICE);
            idCheckType = getIntent().getStringExtra(ID_CHECK_TYPE);
            checkTypeName = getIntent().getStringExtra(CHECK_TYPE_NAME);
            longLat = getIntent().getStringExtra(LOCATION);
        }

        // Setting digit rfid card using MAX_NUMBER = 10
        /* FORMAT "%010d"
         * % ==> used as formatter, 0 ==> used to pad with zeroes instead of spaces
         * 10 ==> maximum of 10 characters wide
         * d ==> as a decimal integer */
        if (numberRfidTemp != null) {
            if (numberRfidTemp.length() < 10) {
                numberRfid = String.format(Locale.getDefault(), "%010d", Integer.valueOf(numberRfidTemp));
            } else {
                numberRfid = numberRfidTemp;
            }
        }

        initView();
        loadingdata();
        setStatusScan();
        initEvent();
    }

    @SuppressLint("SetTextI18n")
    private void initView() {
        binding.tvRfidNumber.setText(numberRfid);

        problemsList = new ArrayList<>();
        adapter = new ProblemGroupAdapter(this);

        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        binding.rvDocumentProblem.setLayoutManager(layoutManager);
        binding.rvDocumentProblem.setItemAnimator(new DefaultItemAnimator());
        binding.rvDocumentProblem.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        binding.rvDocumentProblem.setAdapter(adapter);
    }

    private void loadingdata() {
        problemsList.clear();
        String[] expand = {"employee.company, employee.structuralPosition, employee.functionalPosition, problems.documentType.category,problems.documentType.group"};
        presenter.checkRfidCard(numberRfid, Integer.valueOf(idPermit), idDevice, Integer.valueOf(idCheckType), longLat, expand);
    }

    private void initEvent() {
        binding.btnHome.setOnClickListener(v -> {
            final Intent intent = new Intent(this, HomeActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        });

        binding.btnScanAgain.setOnClickListener(v -> finish());
    }

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

    @Override
    public void showDataRfid(DataResultRfid dataResultRfid) {

        if (dataResultRfid.getEmployee() != null) {
            dataUrl = Constant.URL_PHOTO + dataResultRfid.getEmployee().getUrlPhoto().substring(14);

            binding.tvProfileName.setText(dataResultRfid.getEmployee().getName());
            binding.tvStructuralPosition.setText(dataResultRfid.getEmployee().getStructuralPosition().getName());
            binding.tvFunctionalPosition.setText(dataResultRfid.getEmployee().getFunctionalPosition().getName());
            binding.tvCompanyName.setText(dataResultRfid.getEmployee().getCompany().getName());
        } else {
            binding.tvProfileName.setText("-");
            binding.tvStructuralPosition.setText("-");
            binding.tvFunctionalPosition.setText("-");
            binding.tvCompanyName.setText("-");
        }

        Glide.with(this)
                .load(dataUrl)
                .placeholder(R.drawable.ic_profile_default)
                .error(R.drawable.ic_profile_default)
                .into(binding.ivProfileImage);

        if (dataResultRfid.getPassed()) {
            binding.tvProfileStatus.setText(R.string.label_status_passed);
            binding.llProfileStatus.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
        } else {
            if (dataResultRfid.getAlertType() != null) {
                if (dataResultRfid.getAlertType().equalsIgnoreCase("ERROR")) {
                    binding.tvProfileStatus.setText(R.string.label_status_not_passed);
                    binding.llProfileStatus.setBackgroundColor(getResources().getColor(R.color.colorRedDark));
                }

                if (dataResultRfid.getAlertType().equalsIgnoreCase("WARNING")) {
                    binding.tvProfileStatus.setText(R.string.label_status_not_valid);
                    binding.llProfileStatus.setBackgroundColor(getResources().getColor(R.color.colorRedDark));
                }

            } else {
                binding.tvProfileStatus.setText(R.string.label_status_not_passed);
                binding.llProfileStatus.setBackgroundColor(getResources().getColor(R.color.colorRedDark));
            }
        }

        if (dataResultRfid.getMessage() != null) {
            binding.tvMessage.setVisibility(View.VISIBLE);
            binding.tvMessage.setText(dataResultRfid.getMessage());
        } else {
            binding.tvMessage.setVisibility(View.GONE);
        }

        problemsList = dataResultRfid.getProblems();

        // Function mapping data problem by Group
        List<DataGroup> groupList = Stream.of(problemsList)
                .map(v -> v.getDataDocumentType().getGroup())
                .distinctBy(DataGroup::getId)
                .collect(Collectors.toList());

        adapter.updateGroupList(groupList);
        adapter.updateProblemList(problemsList);
        adapter.notifyDataSetChanged();
    }

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

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