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.SpannableString;

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.report.ReportManager;
import it.integry.integrywmsnative.core.rest.consumers.DepositoRESTConsumer;
import it.integry.integrywmsnative.core.rest.consumers.PrinterRESTConsumer;
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;

    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 String mReportName;
    private PrinterRESTConsumer.Type mPrinterType;

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

    public static Intent createIntent(Context context, MtbColt item, boolean canRecoverUl, PrinterRESTConsumer.Type printerType, 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 keyPrinterType = DataCache.addItem(printerType);
        myIntent.putExtra(Key.PrinterType, keyPrinterType);

        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));
        mPrinterType = DataCache.retrieveItem(getIntent().getStringExtra(Key.PrinterType));

        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(), mPrinterType, mReportName);

        recoverFabMenuVisible.set(canRecoverUL);

        initRecyclerView();
        initColloInfo();
    }


    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() {
        mDepositoRESTConsumer.getDepoByCodMdep(mtbColt.get().getCodMdep(), depo -> {
            descrizioneDepo.set("(" + depo.getDescrizione() + ")");
        }, this::onError);
    }


    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.bindings.contenutoBancaleFab.close(true);
        this.onLoadingStarted();

        this.mPrinterRESTConsumer.getAvailablePrinters(SettingsManager.i().getUserSession().getDepo().getCodMdep(), mPrinterType, value -> {
            if (value.size() > 0) {

                try {
                    String reportName = ReportManager.getReportNameLUFromGestione(mtbColt.get().getGestioneEnum());
                    reportName = mReportName != null ? mReportName : reportName;

                    this.mPrinterRESTConsumer.printCollo(value.get(0),
                            mtbColt.get(),
                            1,
                            reportName,
                            () -> {
                                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);
                }

            } else {
                this.onLoadingEnded();
                String errorMessage = "Nessuna stampante configurata";
                this.onError(new Exception(errorMessage));
            }
        }, this::onError);

    }

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


}
