package com.fusi24.entryPermitScanner.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.LinearLayoutManager;

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

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

import timber.log.Timber;

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

        SoundUtil.initSound(this, R.raw.rfid_error);

        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.rvGroupProblem.setLayoutManager(layoutManager);
        binding.rvGroupProblem.setItemAnimator(new DefaultItemAnimator());
        binding.rvGroupProblem.setAdapter(adapter);
    }

    private void loadingdata() {
        problemsList.clear();
        String[] expand = {"employee.company, employee.structuralPosition, employee.functionalPosition, problems.documentType.category,problems.documentType.group"};

        String bebas = "Location = " + longLat;
        Timber.i(bebas);

        presenter.checkRfidCard(numberRfid, Integer.valueOf(idPermit), idDevice, Integer.valueOf(idCheckType), longLat, getSessionManager().getUserId(), 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 (checkTypeName){
            case "Check In" :
                binding.tvStatusScan.setBackground(getDrawable(R.drawable.bg_green_no_rad));
                break;
            case "Check Out" :
            default:
                binding.tvStatusScan.setBackground(getDrawable(R.drawable.bg_blue_no_rad));
                break;
        }
        binding.tvStatusScan.setText(checkTypeName);
    }

    @Override
    public void showDataRfid(DataResultRfid dataResultRfid) {

        if (dataResultRfid.getEmployee() != null) {
            if (getSessionManager().isDevelopment()){
                dataUrl = Constant.BASE_URL_DEV + Constant.URL_PHOTO + dataResultRfid.getEmployee().getUrlPhoto().substring(14);
            } else {
                dataUrl = Constant.BASE_URL_PROD + 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.greenPassed));
        } else {
            SoundUtil.playSound();
            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.redNotPassed));
                }

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

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

        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 = new ArrayList<>();
        groupList.clear();

        // Search if all data problem document not have any group
        if (!dataResultRfid.getPassed()) {
            if (problemsList.size() != 0){
                if (Stream.of(problemsList).allMatch(v -> v.getDataDocumentType().getGroup() == null)) {
                    groupList.add(new DataGroup(1, "No Group", "No Group Document", true));
                } else {
                    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;
    }
}
