package com.fun.airhornprank.activity;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.recyclerview.widget.GridLayoutManager;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import com.fun.airhornprank.R;
import com.fun.airhornprank.adapter.ListAdapter;
import com.fun.airhornprank.data.MyDataBase;
import com.fun.airhornprank.data.Mydata;
import com.fun.airhornprank.databinding.ActivityListBinding;
import com.fun.airhornprank.tool.Mytools;
import com.fun.airhornprank.tool.StaticValue;

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

public class ListActivity extends AppCompatActivity {
    ActivityListBinding binding;
    private List<Mydata> allData = new ArrayList<>();
    private ListAdapter thumAdapter;
    private int color;

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityListBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        EdgeToEdge.enable(this);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.activity_list), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        initData();

        binding.listBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

    }

    private void initData() {
        Intent intent = getIntent();
        color = intent.getIntExtra(StaticValue.KEY_Color, 0);
        String name = intent.getStringExtra(StaticValue.KEY_CategoryName);
        binding.preListTitle.setText(name);
        Mytools.runIO(new Runnable() {
            @Override
            public void run() {
                allData = MyDataBase.getInstance().likeDAO().getlist(name);
                if (!allData.isEmpty()) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            initView(allData);
                        }
                    });
                }
            }
        });
    }

    private void initView(List<Mydata> allData) {
        thumAdapter = new ListAdapter(this, allData, color);
        binding.preListRv.setAdapter(thumAdapter);
        binding.preListRv.setLayoutManager(new GridLayoutManager(this, 3));
    }
}