package it.integry.integrywmsnative.gest.prod_linee_produzione;

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

import androidx.appcompat.widget.AppCompatTextView;
import androidx.databinding.ObservableArrayList;

import java.util.List;

import javax.inject.Inject;

import it.integry.barcode_base_android_library.model.BarcodeScanDTO;
import it.integry.integrywmsnative.MainApplication;
import it.integry.integrywmsnative.R;
import it.integry.integrywmsnative.core.barcode_reader.BarcodeCallbackDTO;
import it.integry.integrywmsnative.core.barcode_reader.BarcodeManager;
import it.integry.integrywmsnative.core.expansion.BaseFragment;
import it.integry.integrywmsnative.core.expansion.RunnableArgs;
import it.integry.integrywmsnative.core.interfaces.IScrollableFragment;
import it.integry.integrywmsnative.core.interfaces.ITitledFragment;
import it.integry.integrywmsnative.databinding.FragmentLineeProdBinding;
import it.integry.integrywmsnative.gest.prod_dettaglio_linea.ProdDettaglioLineaActivity;
import it.integry.integrywmsnative.gest.prod_linee_produzione.dto.ProdLineStatusDTO;
import it.integry.integrywmsnative.gest.prod_linee_produzione.ui.LinesListAdapter;
import it.integry.integrywmsnative.ui.ElevatedToolbar;
import it.integry.integrywmsnative.view.dialogs.base.DialogSimpleInputHelper;
import it.integry.integrywmsnative.view.dialogs.base.DialogSimpleMessageView;

public class ProdLineeProduzioneFragment extends BaseFragment implements ITitledFragment, IScrollableFragment, ProdLineeProduzioneViewModel.Listener {


    @Inject
    ProdLineeProduzioneViewModel mViewModel;

    private final ObservableArrayList<ProdLineStatusDTO> mLinesObservableList = new ObservableArrayList<>();
    private FragmentLineeProdBinding mBinding;
    private ElevatedToolbar mToolbar;
    private int barcodeScannerIstanceID = -1;

    public static ProdLineeProduzioneFragment newInstance() {
        return new ProdLineeProduzioneFragment();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        setRetainInstance(true);
        mBinding = FragmentLineeProdBinding.inflate(inflater, container, false);
        MainApplication.appComponent
                .prodLineeProduzioneComponent()
                .create()
                .inject(this);

        mViewModel.setListener(this);
        mBinding.setLifecycleOwner(this);
        this.initRecyclerView();
        this.initBarcodeReader();

        return mBinding.getRoot();
    }

    @Override
    public void onStart() {
        super.onStart();
        mViewModel.init();
    }


    private void initBarcodeReader() {
        barcodeScannerIstanceID = BarcodeManager.addCallback(new BarcodeCallbackDTO()
                .setOnScanSuccessful(onScanSuccessful)
                .setOnScanFailed(this::onError));
    }

    private final RunnableArgs<BarcodeScanDTO> onScanSuccessful = data -> {
        this.onLoadingStarted();
        this.mViewModel.processBarcodeDTO(data);
    };

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

    public void refreshLineeProd(List<ProdLineStatusDTO> linesList) {
        this.mLinesObservableList.clear();
        if (linesList != null) {

            this.mLinesObservableList.addAll(linesList);
        }
    }

    private void initRecyclerView() {
        this.mViewModel.getProdLinesList().observe(getViewLifecycleOwner(), this::refreshLineeProd);

        LinesListAdapter prodLinesListAdapter = new LinesListAdapter(this.mLinesObservableList);
        this.mBinding.linesMainList.setAdapter(prodLinesListAdapter);

        prodLinesListAdapter
                .setOnItemClicked(this::selectLine)
                .setEmptyView(this.mBinding.linesListEmptyView);

        if (mToolbar != null)
            mToolbar.setRecyclerView(this.mBinding.linesMainList);
    }

    public void requestResources(ProdLineStatusDTO prodLine) {
        this.onLoadingEnded();
        BarcodeManager.disable();
        requireActivity().runOnUiThread(() -> {

            DialogSimpleInputHelper.makeInputDialog(requireContext(), "Inserisci il numero di risorse da allocare", prodLine.getQtaAllocate().toString(), "n. risorse", qta -> {
                this.onLoadingStarted();
                try {
                    Integer hrNum = Integer.parseInt(qta);
                    this.mViewModel.startProductionLine(prodLine, hrNum);
                } catch (NumberFormatException ex) {
                    this.onError(new Exception("Inserire un numero di risorse valido"));
                }
            }, BarcodeManager::enable, InputType.TYPE_CLASS_NUMBER).show();
        });
    }

    @Override
    public void successDialog(String message, Runnable onComplete) {
        BarcodeManager.disable();
        requireActivity().runOnUiThread(() -> DialogSimpleMessageView.makeSuccessDialog(getResources().getString(R.string.success),
                new SpannableString(message), null, onComplete).show(getChildFragmentManager(), "successDialog"));

    }

    @Override
    public void selectLine(ProdLineStatusDTO dto) {
        this.onLoadingEnded();
        BarcodeManager.disable();

        if (!dto.isStarted()) {
            this.requestResources(dto);
        } else {
            requireActivity().startActivity(ProdDettaglioLineaActivity.newInstance(requireActivity(), dto));
        }
    }


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