package com.idle.wall.idleactivity;

import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentTransaction;
import com.idle.wall.R;
import com.idle.wall.ad.AdsInsUtil;
import com.idle.wall.ad.LoadListener;
import com.idle.wall.ad.ShowListener;
import com.idle.wall.idlefragment.FragmentIdleRecent;
import com.idle.wall.RecentManager;
import com.idle.wall.idletool.Comutils;
import com.tradplus.ads.base.bean.TPAdInfo;

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

public class IdleRecentActivity extends BaseActivity {

    private ImageView ivBack;
    private TextView tvClearAll;
    private FragmentIdleRecent recentFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_idle_recent);
        Comutils.initFull(this, false);
        ivBack = findViewById(R.id.iv_back);
        tvClearAll = findViewById(R.id.tv_clear_all);
        initFragment();
        ivBack.setOnClickListener(v -> onInterceptBackPressed());
        tvClearAll.setOnClickListener(v -> clearAllRecentWallpapers());
    }
    private void initFragment() {
        recentFragment = FragmentIdleRecent.newInstance();
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.fragment_container, recentFragment);
        transaction.commit();
    }

    private void clearAllRecentWallpapers() {
        RecentManager.getInstance(this).clearRecentWallpapers();
        Toast.makeText(this, R.string.recentclean, Toast.LENGTH_SHORT).show();
        // 刷新Fragment中的列表
        if (recentFragment != null) {
            recentFragment.refreshWallpaperList();
        }
    }



    @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) {

            }
        });
    }
}