package it.integry.integrywmsnative.gest.contab_doc_interni;


import android.content.Context;
import android.os.Bundle;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.appcompat.widget.AppCompatTextView;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ObservableArrayList;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.annimon.stream.Stream;

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

import javax.inject.Inject;

import it.integry.integrywmsnative.MainApplication;
import it.integry.integrywmsnative.R;
import it.integry.integrywmsnative.core.data_store.db.entity.SqlMtbColt;
import it.integry.integrywmsnative.core.data_store.db.wrappers.DocInternoWrapper;
import it.integry.integrywmsnative.core.expansion.BaseFragment;
import it.integry.integrywmsnative.core.interfaces.IScrollableFragment;
import it.integry.integrywmsnative.core.interfaces.ITitledFragment;
import it.integry.integrywmsnative.core.utility.UtilityDate;
import it.integry.integrywmsnative.databinding.FragmentDocInterniBinding;
import it.integry.integrywmsnative.gest.contab_doc_interni.dialog.DialogSelectDocInfoView;
import it.integry.integrywmsnative.gest.contab_doc_interni.dialog.DialogSelectDocInfoViewModel;
import it.integry.integrywmsnative.gest.contab_doc_interni.dto.DocInterniSetupDTO;
import it.integry.integrywmsnative.gest.contab_doc_interni.dto.GrigliaAcquistiDTO;
import it.integry.integrywmsnative.gest.contab_doc_interni.edit_form.DocInterniEditFormActivity;
import it.integry.integrywmsnative.gest.contab_doc_interni.ui.DocInterniListAdapter;
import it.integry.integrywmsnative.gest.contab_doc_interni.ui.DocInterniListModel;
import it.integry.integrywmsnative.ui.ElevatedToolbar;

public class DocInterniFragment extends BaseFragment implements ITitledFragment, IScrollableFragment, DocInterniViewModel.Listener {

    @Inject
    DocInterniViewModel mViewModel;

    private final ObservableArrayList<DocInterniListModel> mDocInterniMutableData = new ObservableArrayList<>();
    private ElevatedToolbar mToolbar;
    private FragmentDocInterniBinding mBinding;
    private DocInterniSetupDTO mDocInterniSetupDTO;
    private final List<Runnable> mOnPreDestroyList = new ArrayList<>();
    private boolean dialogInitialized = false;


    public DocInterniFragment() {
        // Required empty public constructor
    }

    public static DocInterniFragment newInstance() {
        DocInterniFragment fragment = new DocInterniFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreateActionBar(AppCompatTextView titleText, Context context) {
        titleText.setText(context.getText(R.string.doc_interni).toString());
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_doc_interni, container, false);
        MainApplication.appComponent
                .docInterniComponent()
                .create()
                .inject(this);

        mViewModel.setListeners(this);
        mBinding.setLifecycleOwner(this);
        mBinding.setView(this);
        mBinding.setViewModel(mViewModel);
        mViewModel.mtbGrup.observe(getViewLifecycleOwner(), mtbGrup -> mViewModel.fetchProducts());
        mViewModel.dtbTipi.observe(getViewLifecycleOwner(), dtbTipi -> mViewModel.fetchDocuments());
        this.initRecyclerView();

        return mBinding.getRoot();
    }

    @Override
    public void onStart() {
        super.onStart();
        if (!this.mViewModel.hasDocDetails()) {
            mViewModel.init();
        } else {
            this.mViewModel.fetchDocuments();
        }
    }

    @Override
    public void onDestroy() {
        for (Runnable onPreDestroy : mOnPreDestroyList) {
            onPreDestroy.run();
        }
        super.onDestroy();
    }

    @Override
    public void onDocInterniSetupFetched(DocInterniSetupDTO docInterniSetupDTO) {
        this.mDocInterniSetupDTO = docInterniSetupDTO;
        this.dialogInitialized = true;
        this.selectDocInfo();
    }

    @Override
    public void onDocDetailsChanged(DialogSelectDocInfoViewModel selection) {
        if (selection.isInputValid()) {
            mViewModel.setSelectedDocDetails(selection);
            mBinding.mainFab.setVisibility(View.VISIBLE);
        } else {
            mBinding.mainFab.setVisibility(View.GONE);
        }

        if (selection.requiresFornitore()) {
            mBinding.codAnagContainer.setVisibility(View.VISIBLE);
        } else {
            mBinding.codAnagContainer.setVisibility(View.GONE);
        }


        if (selection.getSelectedGruppoArt() != null) {
            mBinding.mtbGrpContainer.setVisibility(View.VISIBLE);
        } else {
            mBinding.mtbGrpContainer.setVisibility(View.GONE);
        }

        if (selection.requiresDocData()) {
            mBinding.docContainer.setVisibility(View.VISIBLE);
            mBinding.document.setText(Html.fromHtml(getString(R.string.doc_testata, String.valueOf(selection.getNumDoc()), UtilityDate.formatDate(selection.getDataDoc(), UtilityDate.COMMONS_DATE_FORMATS.DMY_HUMAN))));
        } else {
            mBinding.docContainer.setVisibility(View.GONE);
        }

    }

    @Override
    public void setScrollToolbar(ElevatedToolbar toolbar) {
        mToolbar = toolbar;
    }

    @Override
    public void addOnPreDestroy(Runnable onPreDestroy) {
        this.mOnPreDestroyList.add(onPreDestroy);
    }

    public void selectDocInfo() {
        if (this.dialogInitialized) {
            DialogSelectDocInfoView.newInstance(
                    mDocInterniSetupDTO,
                    this.mViewModel.dtbTipi.getValue(),
                    this.mViewModel.mtbGrup.getValue(),
                    this.mViewModel.fornitore.getValue(),
                    this.mViewModel.dataDoc.getValue(),
                    this.mViewModel.numDoc.getValue(),
                    this.mViewModel.note.getValue(),
                    this::onDocDetailsChanged
            ).show(requireActivity().getSupportFragmentManager(), "tag");
        }
    }

    private void initRecyclerView() {
        this.mViewModel.getDocsList().observe(getViewLifecycleOwner(), this::refreshList);
        DocInterniListAdapter docInterniListAdapter = new DocInterniListAdapter(this.requireActivity(), this.mDocInterniMutableData);
        docInterniListAdapter.setEmptyView(this.mBinding.docInterniEmptyView);
        this.mBinding.docInterniMainList.setAdapter(docInterniListAdapter);
        this.mBinding.docInterniMainList.setLayoutManager(new LinearLayoutManager(this.requireActivity()));

        docInterniListAdapter.setOnItemClicked(this.mViewModel::editDocument);
        if (mToolbar != null)
            mToolbar.setRecyclerView(this.mBinding.docInterniMainList);
    }

    private void refreshList(List<DocInternoWrapper> filteredList) {
        this.mDocInterniMutableData.clear();
        this.mDocInterniMutableData.addAll(convertDataModelToListModel(mViewModel.getDocsList().getValue()));
    }

    private List<DocInterniListModel> convertDataModelToListModel(List<DocInternoWrapper> dataList) {

        return Stream.of(dataList)
                .map(x -> {
                    DocInterniListModel listModel = new DocInterniListModel();
                    listModel.setDocument(x.getDocument());
                    listModel.setProductsCount(x.getCountArticoli());
                    return listModel;
                })
                .toList();

    }

    @Override
    public void onDocumentEditRequest(SqlMtbColt document, GrigliaAcquistiDTO arts) {
        requireActivity().startActivity(DocInterniEditFormActivity.newInstance(requireActivity(), document, arts, mViewModel.getTipoDoc()));
    }
}
