package com.ar.artracestudio.activity;

import android.content.Intent;
import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.GridLayoutManager;

import com.ar.artracestudio.adapter.FavoriteAdapter;
import com.ar.artracestudio.databinding.ActivityImageBinding;
import com.ar.artracestudio.room.AppDatabase;
import com.ar.artracestudio.room.ImageEntry;
import com.ar.artracestudio.utils.ItemDecoration;

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

public class ImageActivity extends AppCompatActivity {

    private ActivityImageBinding binding;
    private String original;
    private String title;
    private FavoriteAdapter adapter;

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

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

        initData();
        initEvent();
        setRecyclerview();

        loadImages();
    }

    private void initData() {

        Intent intent = getIntent();
        original = intent.getStringExtra("Original");
        title = intent.getStringExtra("Title");

    }

    private void initEvent() {
        binding.title.setText(title);

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

    private void setRecyclerview() {
        binding.recyclerview.setLayoutManager(new GridLayoutManager(this, 2));
        adapter = new FavoriteAdapter(this, new ArrayList<>());
        binding.recyclerview.setAdapter(adapter);

        ItemDecoration itemDecoration = new ItemDecoration(16, 19, 10);
        binding.recyclerview.addItemDecoration(itemDecoration);
    }

    private void loadImages() {
        // 获取数据库实例并调用查询方法
        AppDatabase.getInstance(this)
                .imageEntryDao()
                .getImagesByCategoryLive(original)
                .observe(this, new Observer<List<ImageEntry>>() {
                    @Override
                    public void onChanged(List<ImageEntry> imageEntries) {
                        adapter.updateData(imageEntries);
                    }
                });
    }

}