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 android.widget.ImageView;

import java.util.Arrays;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
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.services.kvv.types.Resource;
import de.sebse.fuplanner.tools.MainActivityListener;
import de.sebse.fuplanner.tools.logging.Logger;
import de.sebse.fuplanner.tools.ui.treeview.DirectoryNodeBinder;
import de.sebse.fuplanner.tools.ui.treeview.FileNodeBinder;
import de.sebse.fuplanner.tools.ui.treeview.TreeNode;
import de.sebse.fuplanner.tools.ui.treeview.TreeViewAdapter;

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

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


    public ModDetailResourceFragment() {
        // 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 ModDetailResourceFragment newInstance(String itemPosition) {
        ModDetailResourceFragment fragment = new ModDetailResourceFragment();
        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
        Context context = view.getContext();
        RecyclerView recyclerView = view.findViewById(R.id.list);
        recyclerView.setLayoutManager(new LinearLayoutManager(context));

        adapter = new ModDetailResourceAdapter(Arrays.asList(new FileNodeBinder(), new DirectoryNodeBinder()));
        adapter.setOnTreeNodeListener(new TreeViewAdapter.OnTreeNodeListener() {
            @Override
            public boolean onClick(TreeNode node, RecyclerView.ViewHolder holder) {
                if (!node.isLeaf()) {
                    // Update and toggle the node.
                    onToggle(!node.isExpand(), holder);
                } else if (node.getContent() instanceof Resource.File && ModDetailResourceFragment.this.mListener != null) { // if leaf is file
                    ModDetailResourceFragment.this.mListener.getKVV().modules().resources().recv(mItemPos, (Modules.Module module) -> {
                        String folderName = "FU-"+module.title.replaceAll("[:*<>|/\"\\\\]", "-");
                        Resource.File file = (Resource.File) node.getContent();
                        getDownload().openDownloadDialog(file, folderName);
                    }, log::e);
                }
                return false;
            }

            @Override
            public void onToggle(boolean isExpand, RecyclerView.ViewHolder holder) {
                DirectoryNodeBinder.ViewHolder dirViewHolder = (DirectoryNodeBinder.ViewHolder) holder;
                final ImageView ivArrow = dirViewHolder.getIvArrow();
                int rotateDegree = isExpand ? 90 : -90;
                ivArrow.animate().rotationBy(rotateDegree).start();
            }
        });

        recyclerView.setAdapter(adapter);

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

        return view;
    }

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

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

    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);
    }

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






}
