package com.key.vibekeyboard.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.Adapter.CategoryRecyclerViewAdapter;
import com.key.vibekeyboard.Room.Category;
import com.key.vibekeyboard.Room.WallpaperInfo;
import com.key.vibekeyboard.Utils.ItemDecoration;
import com.key.vibekeyboard.Utils.Mytool;
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 = Mytool.parseJsonToList("keyboard.json");

    public CategoryFragment() {

    }

    // 工厂方法，用于创建 Fragment 的实例，并通过 Bundle 传递类别参数。
    public static CategoryFragment newInstance(String category) {
        CategoryFragment fragment = new CategoryFragment();
        Bundle args = new Bundle();
        args.putString(ARG_CATEGORY, category);  // 将类别参数存储到 Bundle 中。
        fragment.setArguments(args);  // 将 Bundle 设置为 Fragment 的参数。
        return fragment;
    }
    // 当 Fragment 创建时调用，用于初始化一些变量。
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 如果 Fragment 有传入的参数，则获取并存储类别名称。
        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);

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

        // 为 RecyclerView 添加自定义的间距装饰。
        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; // 释放 ViewBinding 的引用
    }

}