package com.ar.ardrawingboard.ui.activity;

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

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

import com.ar.ardrawingboard.topon.AdManager;
import com.ar.ardrawingboard.topon.onActionListener;
import com.ar.ardrawingboard.ui.adapter.FavoriteAndCategoryAdapter;
import com.ar.ardrawingboard.databinding.ActivityCategoryBinding;
import com.ar.ardrawingboard.room.AppDatabase;
import com.ar.ardrawingboard.util.ItemDecoration;

import java.util.ArrayList;

public class CategoryActivity extends AppCompatActivity {
    private ActivityCategoryBinding mBinding;
    private String mCategoryKey;
    private String mCategoryTitle;
    private FavoriteAndCategoryAdapter mAdapter;

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

        mBinding = ActivityCategoryBinding.inflate(getLayoutInflater());
        setContentView(mBinding.getRoot());

        AdManager.loadAllAd();
        AdManager.showTopOn(this, new onActionListener() {
            @Override
            public void onAction() {

            }
        });

        extractIntentData();
        setupUI();
        configureRecyclerView();
        fetchAndDisplayImages();
    }

    private void extractIntentData() {
        Intent dataIntent = getIntent();
        mCategoryKey = dataIntent.getStringExtra("Original");
        mCategoryTitle = dataIntent.getStringExtra("Title");
    }

    private void setupUI() {
        mBinding.title.setText(mCategoryTitle);

        mBinding.back.setOnClickListener(view -> {
            AdManager.showTopOn(this, new onActionListener() {
                @Override
                public void onAction() {
                    finish();
                }
            });
        });
    }

    private void configureRecyclerView() {
        GridLayoutManager layoutManager = new GridLayoutManager(this, 2);
        mBinding.recyclerview.setLayoutManager(layoutManager);

        mAdapter = new FavoriteAndCategoryAdapter(this, new ArrayList<>());
        mBinding.recyclerview.setAdapter(mAdapter);

        ItemDecoration spacingDecoration = new ItemDecoration(16, 19, 10);
        mBinding.recyclerview.addItemDecoration(spacingDecoration);
    }

    private void fetchAndDisplayImages() {
        AppDatabase database = AppDatabase.getInstance(this);

        database.boardEntryDao()
                .getImageByPath(mCategoryKey)
                .observe(this, entries -> {
                    if (entries != null) {
                        mAdapter.refreshFavorites(entries);
                    }
                });
    }
}
