package com.ardraw.ardrawinggallery.activity;

import android.os.Bundle;
import android.util.Log;

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.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.GridLayoutManager;

import com.ardraw.ardrawinggallery.R;
import com.ardraw.ardrawinggallery.adapter.GalleryAdapter;
import com.ardraw.ardrawinggallery.databinding.ActivitySubBinding;
import com.ardraw.ardrawinggallery.room.ArData;
import com.ardraw.ardrawinggallery.util.DatabaseUtil;
import com.ardraw.ardrawinggallery.util.ItemDecoration;

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

public class SubActivity extends AppCompatActivity {
    private ActivitySubBinding binding;
    private GalleryAdapter adapter;
    private DatabaseUtil databaseUtil;
    private String title;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivitySubBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        EdgeToEdge.enable(this);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        initData();
        initEvent();
    }

    private void initData() {
        String path = getIntent().getStringExtra("Path");
        if (path == null) {
            finish();
            return;
        }

        String[] parts = path.split("/");
        title = parts[0].split("_")[1];

        databaseUtil = new DatabaseUtil(this);

        binding.recyclerView.setLayoutManager(new GridLayoutManager(this, 2));
        adapter = new GalleryAdapter(new ArrayList<>(), this,  1);
        binding.recyclerView.setAdapter(adapter);

        ItemDecoration itemDecoration = new ItemDecoration(35, 15, 20);
        binding.recyclerView.addItemDecoration(itemDecoration);
    }

    private void initEvent() {
        binding.back.setOnClickListener(v -> finish());
        binding.text.setText(title);
        loadImage();
    }

    private void loadImage() {
        Log.d("TAG", "loadImage: " + title);
        databaseUtil
                .getListByName(title)
                .observe(this, new Observer<List<ArData>>() {
                    @Override
                    public void onChanged(List<ArData> arData) {
                        adapter.updateData(arData);
                        Log.d("TAG", "onChanged: " + arData.size());
                    }
                });
    }

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