package it.integry.integrywmsnative.gest.contenuto_bancale;

import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.text.Html;
import android.text.SpannableString;
import android.view.Gravity;

import androidx.appcompat.widget.PopupMenu;
import androidx.core.content.ContextCompat;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ObservableField;
import androidx.recyclerview.widget.LinearLayoutManager;

import javax.inject.Inject;

import it.integry.integrywmsnative.MainApplication;
import it.integry.integrywmsnative.R;
import it.integry.integrywmsnative.core.data_cache.DataCache;
import it.integry.integrywmsnative.core.expansion.BaseActivity;
import it.integry.integrywmsnative.core.model.MtbColt;
import it.integry.integrywmsnative.core.rest.consumers.ColliMagazzinoRESTConsumer;
import it.integry.integrywmsnative.core.rest.consumers.DepositoRESTConsumer;
import it.integry.integrywmsnative.core.rest.consumers.PrinterRESTConsumer;
import it.integry.integrywmsnative.core.rest.model.uds.DeleteULRequestDTO;
import it.integry.integrywmsnative.core.settings.SettingsManager;
import it.integry.integrywmsnative.databinding.ActivityContenutoBancaleBinding;
import it.integry.integrywmsnative.gest.contenuto_bancale.ui.ContenutoBancaleListAdapter;
import it.integry.integrywmsnative.ui.SimpleDividerItemDecoration;
import it.integry.integrywmsnative.view.dialogs.base.DialogSimpleMessageView;

public class ContenutoBancaleActivity extends BaseActivity implements ContenutoBancaleViewModel.Listener {

    public ActivityContenutoBancaleBinding bindings;

    @Inject
    ContenutoBancaleViewModel mViewModel;

    @Inject
    DepositoRESTConsumer mDepositoRESTConsumer;

    @Inject
    PrinterRESTConsumer mPrinterRESTConsumer;

    @Inject
    ColliMagazzinoRESTConsumer mColliMagazzinoRESTConsumer;

    public final ObservableField<MtbColt> mtbColt = new ObservableField<>();
    public final ObservableField<String> descrizioneDepo = new ObservableField<>();
    public ObservableField<Boolean> fabVisible = new ObservableField<>(true);
    public ObservableField<Boolean> recoverFabMenuVisible = new ObservableField<>(false);
    private PopupMenu fabPopupMenu;

    private String mReportName;

    private static class Key {
        private static final String MtbColtKey = "mtbColtKey";
        private static final String CanRecoverUL = "canRecoverUL";
        private static final String ReportName = "reportName";
    }

    public static Intent createIntent(Context context, MtbColt item, boolean canRecoverUl, String reportName) {
        Intent myIntent = new Intent(context, ContenutoBancaleActivity.class);

        String keyMtbColt = DataCache.addItem(item);
        myIntent.putExtra(Key.MtbColtKey, keyMtbColt);

        String keyCanRecoverUL = DataCache.addItem(canRecoverUl);
        myIntent.putExtra(Key.CanRecoverUL, keyCanRecoverUL);

        String keyReportName = DataCache.addItem(reportName);
        myIntent.putExtra(Key.ReportName, keyReportName);

        return myIntent;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        boolean canRecoverUL = DataCache.retrieveItem(getIntent().getStringExtra(Key.CanRecoverUL));
        mtbColt.set(DataCache.retrieveItem(getIntent().getStringExtra(Key.MtbColtKey)));
        mReportName = DataCache.retrieveItem(getIntent().getStringExtra(Key.ReportName));

        bindings = DataBindingUtil.setContentView(this, R.layout.activity_contenuto_bancale);

        MainApplication.appComponent
                .contenutoBancaleComponent()
                .create()
                .inject(this);

        bindings.setView(this);
        bindings.setViewModel(this.mViewModel);

        bindings.elevatedToolbar.setNestedScrollView(bindings.scrollView);

        setSupportActionBar(this.bindings.toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        mViewModel.setListener(this);
        mViewModel.init(mtbColt.get(), mReportName);

        recoverFabMenuVisible.set(canRecoverUL);

        this.initRecyclerView();
        this.initColloInfo();
        this.initFab();
    }

    private void initRecyclerView() {
        this.bindings.contenutoBancaleMainList.setNestedScrollingEnabled(false);

        this.bindings.contenutoBancaleMainList.setHasFixedSize(true);

        this.bindings.contenutoBancaleMainList.setLayoutManager(new LinearLayoutManager(this));

        SimpleDividerItemDecoration itemDecorator = new SimpleDividerItemDecoration(this, SimpleDividerItemDecoration.VERTICAL);
        itemDecorator.setDrawable(ContextCompat.getDrawable(this, R.drawable.divider));
        this.bindings.contenutoBancaleMainList.addItemDecoration(itemDecorator);

        ContenutoBancaleListAdapter adapter = new ContenutoBancaleListAdapter(mtbColt.get().getMtbColr());
        this.bindings.contenutoBancaleMainList.setAdapter(adapter);
    }

    private void initColloInfo() {
        SettingsManager.iDB().getAvailableCodMdep().stream()
                .filter(x -> x.getCodMdep().equalsIgnoreCase(mtbColt.get().getCodMdep()))
                .findFirst()
                .ifPresent(x -> descrizioneDepo.set("(" + x.getDescrizione() + ")"));
    }

    private void initFab() {
        fabPopupMenu = new PopupMenu(this, this.bindings.accettazioneOrdineInevasoFab,
                (Gravity.END | Gravity.BOTTOM),
                androidx.appcompat.R.attr.popupMenuStyle,
                com.google.android.material.R.style.Widget_Material3_PopupMenu_ContextMenu);

        fabPopupMenu.setForceShowIcon(true);
        fabPopupMenu.getMenuInflater().inflate(R.menu.contenuto_bancale_fab_menu, fabPopupMenu.getMenu());

        if (mtbColt.get().isDocumentPresent()) {
            fabPopupMenu.getMenu().removeItem(R.id.delete_ul);
        }

        fabPopupMenu.setOnMenuItemClickListener(item -> {
            int itemId = item.getItemId();

            if (itemId == R.id.recover_ul) {
                this.recoverUL();
            } else if (itemId == R.id.print_ul) {
                this.printUL();
            } else if (itemId == R.id.delete_ul) {
                this.deleteUL();
            }

            return false;
        });
    }

    public void recoverUL() {
        Intent data = new Intent();
        String key = DataCache.addItem(mtbColt.get());
        data.putExtra("key", key);

        this.setResult(RESULT_OK, data);
        this.finish();
    }

    public void printUL() {
        this.onLoadingStarted();
        try {
            this.mPrinterRESTConsumer.printCollo(mtbColt.get(),
                    () -> {
                        this.onLoadingEnded();

                        Resources res = this.getResources();
                        String errorMessage = res.getText(R.string.alert_print_completed_message).toString();
                        DialogSimpleMessageView
                                .makeSuccessDialog(res.getText(R.string.completed).toString(), new SpannableString(errorMessage), null, null)
                                .show(getSupportFragmentManager(), "tag");
                    }, this::onError);

        } catch (Exception ex) {
            this.onError(ex);
        }
    }

    public void deleteUL() {
        String text = getResources().getString(R.string.alert_delete_UL);

        DialogSimpleMessageView.makeWarningDialog(new SpannableString(Html.fromHtml(text)), null, () -> this.runOnUiThread(() -> {
            this.onLoadingStarted();

            try {
                DeleteULRequestDTO deleteULRequestDTO = new DeleteULRequestDTO()
                        .setMtbColt(this.mtbColt.get());

                mColliMagazzinoRESTConsumer.deleteUL(deleteULRequestDTO, () -> {
                    Intent data = new Intent();
                    String key = DataCache.addItem(this.mtbColt.get());
                    String keyDeleteUL = DataCache.addItem(true);
                    data.putExtra("key", key)
                            .putExtra("keyDeleteUL", keyDeleteUL);

                    this.onLoadingEnded();
                    this.setResult(RESULT_OK, data);
                    this.finish();
                }, this::onError);
            } catch (Exception ex) {
                this.onError(ex);
            }
        }), () -> {
        }).show(this.getSupportFragmentManager(), "tag");
    }

    public void showFabMenu() {
        fabPopupMenu.show();
    }

    @Override
    public boolean onSupportNavigateUp() {
        getOnBackPressedDispatcher().onBackPressed();
        return true;
    }

}
