package com.key.vibekeyboard.ui.fragment;

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.GridLayoutManager;

import com.key.vibekeyboard.ui.adapter.WallpaperAdapter;
import com.key.vibekeyboard.data.bean.Category;
import com.key.vibekeyboard.data.database.entity.WallpaperInfo;
import com.key.vibekeyboard.utils.ItemDecoration;
import com.key.vibekeyboard.utils.JsonUtils;
import com.key.vibekeyboard.databinding.FragmentCategoryBinding;

import java.util.ArrayList;
import java.util.List;


public class CategoryFragment extends Fragment {

    private static final String ARG_CATEGORY = "category";
    private FragmentCategoryBinding binding;
    private String category;
    private final List<Category> categories = JsonUtils.parseJson("keyboard.json");

    public CategoryFragment() {

    }

    public static CategoryFragment newInstance(String category) {
        CategoryFragment fragment = new CategoryFragment();
        Bundle args = new Bundle();
        args.putString(ARG_CATEGORY, category);
        fragment.setArguments(args);
        return fragment;
    }

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

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        binding = FragmentCategoryBinding.inflate(inflater, container, false);

        List<WallpaperInfo> list = getListByClassName(category);

        WallpaperAdapter adapter = new WallpaperAdapter(requireContext(),list);
        binding.categoryRecycler.setAdapter(adapter);
        binding.categoryRecycler.setLayoutManager(new GridLayoutManager(getContext(), 2));

        ItemDecoration itemDecoration = new ItemDecoration(12, 10, 9);
        binding.categoryRecycler.addItemDecoration(itemDecoration);
        return binding.getRoot();
    }

    public List<WallpaperInfo> getListByClassName(String className) {
        for (Category category : categories) {
            if (category.getClassName().equals(className)) {
                return category.getList();
            }
        }
        return new ArrayList<>();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        binding = null;
    }

}