package com.draw.painting.test.ui;

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

import android.os.Bundle;
import android.view.View;

import com.applovin.mediation.MaxAd;
import com.applovin.mediation.ads.MaxInterstitialAd;
import com.draw.painting.test.Adcallback;
import com.draw.painting.test.PaintingApp;
import com.draw.painting.test.adapter.PreViewAdapter;
import com.draw.painting.test.databinding.ActivityPreViewBinding;
import com.draw.painting.test.manager.Utils;

import java.util.List;

public class PreViewActivity extends AppCompatActivity {

    private ActivityPreViewBinding preViewBinding;

    private String dirStr;
    private static List<MaxInterstitialAd> adsList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        preViewBinding = ActivityPreViewBinding.inflate(getLayoutInflater());
        setContentView(preViewBinding.getRoot());
        Utils.setStatusBarTextColor(this, true);
        dirStr = getIntent().getStringExtra(PaintingApp.Key_ViewDir);
        preViewBinding.categoryName.setText(dirStr.substring(dirStr.lastIndexOf("_") + 1));

        adsList = Utils.getAllAd();

        onInitList();
        onInitClick();
    }

    private void onInitList() {

        List<String> list = Utils.fileExistsInAssets(this, dirStr);

        PreViewAdapter preViewAdapter = new PreViewAdapter(this, list);
        preViewBinding.recyclerview.setAdapter(preViewAdapter);
        preViewBinding.recyclerview.setLayoutManager(new GridLayoutManager(this, 3));
    }

    private void onInitClick() {
        preViewBinding.back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showAd();
            }
        });
    }

    private void showAd() {
        MaxInterstitialAd cachedAd = Utils.onCache(adsList);
        if (cachedAd == null) {
            finish();
        } else {
            Utils.setCallBcak(cachedAd, new Adcallback() {
                @Override
                public void onShowFail(MaxAd ad) {
                    finish();
                }

                @Override
                public void onAdHidden() {
                    finish();
                }
            });
            cachedAd.showAd(this);
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        showAd();
    }
}