package de.sebse.fuplanner.fragments.canteen;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

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 MainActivityListener mListener;
    private final Logger log = new Logger(this);
    private ViewPager mViewPager;
    private DaySwitcherAdapter adapterViewPager;

    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(int canteenId) {
        DaySwitcherFragment fragment = new DaySwitcherFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_POSITION, canteenId);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mCanteenId = getArguments().getInt(ARG_POSITION);
        }
        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);

        refresh(false);

        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(boolean forceRefresh) {
        refresh(forceRefresh, 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);
                adapterViewPager.setModule(canteen);
                browser.getCanteen(canteen, success -> {
                    adapterViewPager.setModule();
                    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);
    }

}
