package com.key.vibekeyboard.Activity;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.key.vibekeyboard.Adapter.SearchRecyclerViewAdapter;
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.ActivitySearchBinding;

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

public class SearchActivity extends AppCompatActivity {

    private ActivitySearchBinding binding;
    private List<Category> categories = Mytool.parseJsonToList("keyboard.json");
    private List<WallpaperInfo> filteredList = new ArrayList<>();
    private SearchRecyclerViewAdapter adapter; // 适配器类

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivitySearchBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        // 设置 RecyclerView
        binding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new SearchRecyclerViewAdapter(filteredList, this);
        // 为 RecyclerView 添加自定义的间距装饰。
        ItemDecoration itemDecoration = new ItemDecoration(12, 10, 9);
        binding.recyclerView.addItemDecoration(itemDecoration);

        binding.recyclerView.setAdapter(adapter);

        binding.back.setOnClickListener(v -> finish());

        // 监听输入框内容变化
        binding.searchEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                filter(charSequence.toString()); // 调用过滤方法
            }

            @Override
            public void afterTextChanged(Editable editable) {
            }
        });
    }

    // 过滤逻辑，根据输入内容过滤数据
    private void filter(String text) {
        filteredList.clear(); // 清空之前的结果

        for (Category category : categories) {
            for (WallpaperInfo wallpaper : category.getList()) {
                if (wallpaper.getTitle().toLowerCase().contains(text.toLowerCase())) {
                    filteredList.add(wallpaper); // 添加匹配的结果
                }
            }
        }

        adapter.notifyDataSetChanged(); // 通知适配器更新数据
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        binding = null; // 释放 ViewBinding 的引用
    }

}
