package de.sebse.fuplanner.fragments.moddetails;


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.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import de.sebse.fuplanner.MainActivity;
import de.sebse.fuplanner.R;
import de.sebse.fuplanner.services.kvv.ui.Download;
import de.sebse.fuplanner.services.kvv.types.Modules;
import de.sebse.fuplanner.tools.MainActivityListener;
import de.sebse.fuplanner.tools.logging.Logger;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link ModDetailAssignmentFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class ModDetailAssignmentFragment extends Fragment implements Download.OnDownloadRequestInterface {
    private static final String ARG_POSITION = "itemPosition";

    private String mItemPos;
    private final Logger log = new Logger(this);
    private ModDetailAssignmentAdapter adapter;
    private SwipeRefreshLayout swipeLayout;
    private Download download;
    @Nullable private MainActivityListener mListener;


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

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param itemPosition Item position in module list.
     * @return A new instance of fragment ModDetailAnnounceFragment.
     */
    public static ModDetailAssignmentFragment newInstance(String itemPosition) {
        ModDetailAssignmentFragment fragment = new ModDetailAssignmentFragment();
        Bundle args = new Bundle();
        args.putString(ARG_POSITION, itemPosition);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mItemPos = getArguments().getString(ARG_POSITION);
        }
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_recycler_view, container, false);
        // Set the adapter
        RecyclerView expandableListView = view.findViewById(R.id.list);
        adapter = new ModDetailAssignmentAdapter(this);
        expandableListView.setAdapter(adapter);

        // Getting SwipeContainerLayout
        swipeLayout = view.findViewById(R.id.swipe_container);
        // Adding Listener
        swipeLayout.setOnRefreshListener(() -> refresh(true));
        refresh(false);

        return view;
    }

    private void refresh(boolean forceRefresh) {
        if (mListener == null)
            return;
        mListener.getKVV().modules().details().recv(mItemPos, pair -> {
            adapter.setModule(pair.first);
            if (pair.second)
                swipeLayout.setRefreshing(false);
        }, error -> {
            swipeLayout.setRefreshing(false);
            log.e(error);
        }, forceRefresh);
    }

    @Override
    public void request(String title, String url) {
        if (mListener == null)
            return;
        mListener.getKVV().modules().list().find(mItemPos, (Modules.Module module) -> {
            String folderName = "FU-"+module.title.replaceAll("[:*<>|/\"\\\\]", "-");
            folderName += "/Assignment";
            getDownload().openDownloadDialog(title, url, folderName);
        }, log::e);
    }

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

    @Override
    public void onDetach() {
        super.onDetach();
        if (this.mListener != null) {
            this.mListener.removeRequestPermissionsResultListener("ModDetailAssignmentFragment");
            this.mListener = null;
        }
    }

    private Download getDownload() {
        if (download == null)
            download = new Download(this::getContext, () -> (MainActivity) getActivity());
        return download;
    }
}
