package com.artisanic.helper.artui;

import android.os.Bundle;

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

import com.artisanic.helper.ArtApp;
import com.artisanic.helper.ad.AdsInsUtil;
import com.artisanic.helper.ad.LoadListener;
import com.artisanic.helper.ad.ShowListener;
import com.artisanic.helper.artadapter.ListAdapter;
import com.artisanic.helper.artmanager.ArtUtils;
import com.artisanic.helper.test.databinding.ActivityListBinding;
import com.tradplus.ads.base.bean.TPAdInfo;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.List;

public class ListActivity extends BaseActivity {

    private ActivityListBinding preViewBinding;
    private String dirStr;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        preViewBinding = ActivityListBinding.inflate(getLayoutInflater());
        setContentView(preViewBinding.getRoot());
        ArtUtils.setStatusBarTextColor(this,true);
        dirStr = getIntent().getStringExtra(ArtApp.Key_ViewDir);
        preViewBinding.categoryName.setText(dirStr.substring(dirStr.lastIndexOf("_")+1));
        onInitList();
        onInitClick();
    }

    private void onInitList() {
        List<String> list = ArtUtils.fileExistsInAssets(this, dirStr);
        ListAdapter preViewAdapter = new ListAdapter(this, list);
        preViewBinding.recyclerview.setAdapter(preViewAdapter);
        preViewBinding.recyclerview.setLayoutManager(new GridLayoutManager(this, 2));
    }

    private void onInitClick() {
        preViewBinding.back.setOnClickListener(v ->onInterceptBackPressed());
    }


    @Override
    protected boolean shouldInterceptBackPress() {
        return true;
    }

    @Override
    protected void onInterceptBackPressed() {
        AdsInsUtil.INSTANCE.showAd(this, AdsInsUtil.Placement.TOP_ON_AD_TOW, new ShowListener() {
            @Override
            public void onAdShown(@Nullable TPAdInfo ad) {
                loadAd();
            }

            @Override
            public void onAdClosed() {
                loadAd();
            }
        });
        if (getBackPressedCallback() != null) {
            getBackPressedCallback().setEnabled(false);
        }
        getOnBackPressedDispatcher().onBackPressed();
    }

    private void loadAd(){
        AdsInsUtil.INSTANCE.loadAd(this, AdsInsUtil.Placement.TOP_ON_AD_TOW, new LoadListener() {
            @Override
            public void loadFailed(@NotNull String error) {

            }
        });
    }
}