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.core.data.JumpInfo;
import com.ads.cal.core.utils.FragmentXUtils;
import com.ads.cal.core.views.fragments.CleanScanFragment;
import com.ads.cal.core.views.fragments.ProcessScanFragment;

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 CleanScanFragment cleanScanFragment;
    private ProcessScanFragment processScanFragment;

    private void init() {
        Intent intent = getIntent();
        int jumpType = intent.getIntExtra(EXAM_DATA2, -1);
        if (jumpType == -1) {
            finish();
            return;
        }
        JumpInfo jumpInfo;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.TIRAMISU) {
            jumpInfo = intent.getSerializableExtra(EXAM_DATA1, JumpInfo.class);
        } else {
            jumpInfo = (JumpInfo) intent.getSerializableExtra(EXAM_DATA1);
        }
        if (jumpInfo != null) {
            if (jumpType == JumpInfo.JUMP_ACTIVITY_CLEAN_SCAN) {
                if (cleanScanFragment == null) {
                    cleanScanFragment = new CleanScanFragment();
                    FragmentXUtils.add(getSupportFragmentManager(), cleanScanFragment, android.R.id.content);
                }
                return;
            }
            if (jumpType == JumpInfo.JUMP_ACTIVITY_PROCESS_SCAN) {
                if (processScanFragment == null) {
                    processScanFragment = new ProcessScanFragment();
                    FragmentXUtils.add(getSupportFragmentManager(), processScanFragment, android.R.id.content);
                }
            }
            return;
        }
        finish();
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (init == 0) {
            init();
        }
    }

    @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);
        startCountdownUpdate(delay);
    }

    @Override
    void intData() {

    }


    // 更新倒计时UI
    private void startCountdownUpdate(long totalTime) {
        final Handler countdownHandler = new Handler();
        countdownHandler.post(new Runnable() {
            long timeLeft = totalTime;

            @Override
            public void run() {
                if (!isPaused && timeLeft > 0) {
                    timeLeft -= 100;
                    countdownHandler.postDelayed(this, 100);
                }
            }
        });
    }

    // 跳转到下一页
    private void navigateToNextPage() {


        finish();
    }
    private void showAds(){
        final WeakReference<Activity> activityRef = new WeakReference<>(this);


    }

    @Override
    protected void onPause() {
        super.onPause();
        isPaused = true;
        if (init == 0) {
            return;
        }
        // 计算剩余时间并移除回调
        long elapsedTime = SystemClock.elapsedRealtime() - startTime;
        remainingTime = Math.max(0, remainingTime - elapsedTime);
        handler.removeCallbacks(jumpRunnable);
    }

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

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

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (init == 0) {
            return;
        }
        // 移除所有回调，防止内存泄漏
        handler.removeCallbacks(jumpRunnable);
    }

    @Override
    public void onBackPressed() {
        if (init == 0) {
            if (cleanScanFragment != null) {
                cleanScanFragment.onBackPressed();
                return;
            }
            if (processScanFragment != null) {
                processScanFragment.onBackPressed();
                return;
            }
        }
        super.onBackPressed();
    }

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

    public static void invoke(Context context, JumpInfo jumpInfo, int jumpType) {
        if (init == 0) {
            Intent intent = new Intent(context, LoadingActivity.class);
            intent.putExtra(EXAM_DATA1, jumpInfo);
            intent.putExtra(EXAM_DATA2, jumpType);
            context.startActivity(intent);
        }
    }

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