package de.sebse.fuplanner.fragments.canteen;

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

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;
import de.sebse.fuplanner.MainActivity;
import de.sebse.fuplanner.R;
import de.sebse.fuplanner.services.canteen.CanteenBrowser;
import de.sebse.fuplanner.services.canteen.types.Canteen;
import de.sebse.fuplanner.tools.MainActivityListener;
import de.sebse.fuplanner.tools.logging.Logger;
import de.sebse.fuplanner.tools.network.NetworkCallback;
import de.sebse.fuplanner.tools.network.NetworkErrorCallback;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link MainActivityListener} interface
 * to handle interaction events.
 * Use the {@link DaySwitcherFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class DaySwitcherFragment extends Fragment implements DaySwitcherListener {
    private static final String ARG_POSITION = "canteenId";

    // Parameters
    private int mCanteenId;
    private String mPageRestoreRequest = null;

    private MainActivityListener mListener;
    private final Logger log = new Logger(this);
    private DaySwitcherAdapter adapterViewPager;
    private ViewPager mViewPager;

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

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param canteenId Canteen id in canteens list.
     * @return A new instance of fragment DaySwitcherFragment.
     */
    public static Fragment newInstance(String canteenId) {
        DaySwitcherFragment fragment = new DaySwitcherFragment();
        Bundle args = new Bundle();
        if (!canteenId.contains("."))
            args.putString(ARG_POSITION, canteenId+".0");
        else
            args.putString(ARG_POSITION, canteenId);

        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            String canteenId = getArguments().getString(ARG_POSITION);
            if (!canteenId.contains(".")) {
                mCanteenId = Integer.parseInt(canteenId);
                mPageRestoreRequest = null;
            } else {
                String[] split = canteenId.split("\\.", 2);
                mCanteenId = Integer.parseInt(split[0]);
                mPageRestoreRequest = split[1];
            }
        }
        if (mListener != null) {
            mListener.onTitleTextChange(R.string.canteens);
            mListener.getCanteenBrowser().getCanteens(success -> {
                Canteen canteen = success.getCanteen(mCanteenId);
                if (mListener != null && canteen != null)
                    mListener.onTitleTextChange(canteen.getName());
            }, log::e);
        }
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.fragment_mod_detail, container, false);

        mViewPager = v.findViewById(R.id.vpPager);
        adapterViewPager = new DaySwitcherAdapter(getChildFragmentManager());
        mViewPager.setAdapter(adapterViewPager);
        applyPageRequest();
        refresh();

        return v;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof MainActivityListener) {
            mListener = (MainActivityListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement MainActivityListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    private void refresh() {
        refresh(false, null, null);
    }

    private void refresh(boolean forceRefresh, NetworkCallback<Canteen> callback, NetworkErrorCallback errorCallback) {
        if (getActivity() != null) {
            CanteenBrowser browser = ((MainActivity) getActivity()).getCanteenBrowser();
            browser.getCanteens(canteens -> {
                Canteen canteen = canteens.getCanteen(mCanteenId);
                canteen.cleanUpDays();
                adapterViewPager.setModule(canteen);
                applyPageRequest();
                browser.getCanteen(canteen, success -> {
                    adapterViewPager.setModule();
                    applyPageRequest();
                    if (callback != null)
                        callback.onResponse(success);
                }, error -> {
                    log.e(error);
                    if (errorCallback != null)
                        errorCallback.onError(error);
                }, forceRefresh);
            }, error -> {
                log.e(error);
                if (errorCallback != null)
                    errorCallback.onError(error);
            }, forceRefresh);
        }
    }

    @Override
    public void onChildRefresh(NetworkCallback<Canteen> callback, NetworkErrorCallback errorCallback) {
        refresh(true, callback, errorCallback);
    }

    public void gotoFragmentPart(int part) {
        mViewPager.setCurrentItem(part, true);
    }

    public String getData() {
        return mCanteenId+"."+mViewPager.getCurrentItem();
    }

    private void applyPageRequest() {
        if (mPageRestoreRequest != null) {
            int request = Integer.parseInt(mPageRestoreRequest);
            mViewPager.setCurrentItem(request);
            if (request == mViewPager.getCurrentItem())
                mPageRestoreRequest = null;
        }
    }
}
