package com.ads.cal.notes;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.ads.cal.notes.callback.OnShowAdEndCallBack;
import com.ads.cal.notes.manager.InterstitialAdManager;

import java.lang.ref.WeakReference;

public class LoadingActivity extends BaseActivity {

    private static final long MIN_DELAY = 2000; // 最小延迟2秒
    private static final long MAX_DELAY = 3000; // 最大延迟3秒

    private Handler handler;
    private Runnable jumpRunnable;
    private long startTime;
    private long remainingTime;
    private boolean isPaused = false;
    private boolean isFinished = false;
    private boolean mHasNavigated = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    int getContentLayoutId() {
        return R.layout.activity_loading;
    }

    @Override
    void initView() {

        // 初始化Handler
        handler = new Handler();
        // 生成随机延迟时间(2-3秒)
        final long delay = MIN_DELAY + (long) (Math.random() * (MAX_DELAY - MIN_DELAY));
        remainingTime = delay;

        // 创建跳转任务
        jumpRunnable = new Runnable() {
            @Override
            public void run() {
                if (!isPaused) {
                    isFinished = true;
                    showAds();
                }
            }
        };

        // 记录开始时间
        startTime = SystemClock.elapsedRealtime();

        // 启动倒计时
        handler.postDelayed(jumpRunnable, delay);
    }

    @Override
    void intData() {

    }

    // 跳转到下一页
    private void navigateToNextPage() {
        if (mHasNavigated) {
            return; // 防止重复跳转
        }

        mHasNavigated = true;
        Intent intent = new Intent(this, ResultActivity.class);
        startActivity(intent);
        finish();
    }

    private void showAds() {
        if (!InterstitialAdManager.getInstance().hasCache()) {
            InterstitialAdManager.getInstance().loadAd();
            navigateToNextPage();
            return;
        }
        InterstitialAdManager.getInstance().setOnShowAdCallBack(new OnShowAdEndCallBack() {
            @Override
            public void onShowAdComplete() {
                navigateToNextPage();
            }

            @Override
            public void onShowAdFailed(String errorMsg) {
                navigateToNextPage();

            }
        });
        final WeakReference<Activity> activityRef = new WeakReference<>(this);
        InterstitialAdManager.getInstance().showInterstitial(activityRef.get());
    }

    @Override
    protected void onPause() {
        super.onPause();
        isPaused = true;

        // 计算剩余时间并移除回调
        long elapsedTime = SystemClock.elapsedRealtime() - startTime;
        remainingTime = Math.max(0, remainingTime - elapsedTime);
        handler.removeCallbacks(jumpRunnable);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isFinished) {
            return;
        }
        if (isPaused && remainingTime > 0) {
            isPaused = false;
            startTime = SystemClock.elapsedRealtime();

            // 重新启动计时器
            handler.postDelayed(jumpRunnable, remainingTime);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 移除所有回调，防止内存泄漏
        if (handler != null && jumpRunnable != null) {
            handler.removeCallbacks(jumpRunnable);
        }
        InterstitialAdManager.getInstance().setOnShowAdCallBack(null);
        InterstitialAdManager.getInstance().setOnLoadAdCallBack(null);
    }

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

    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }


    public static void instance(Context context) {
        Intent intent = new Intent(context, LoadingActivity.class);
        context.startActivity(intent);
    }
}
