package com.github.material.monitor.demo;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.View;

import com.github.material.monitor.FrameCallback;
import com.github.material.monitor.MaterialMonitor;
import com.github.material.monitor.MaterialStyle;
import com.github.material.monitor.demo.helper.DemoMonitorConfig;
import com.github.material.monitor.demo.helper.MaterialMonitorHelper;
import com.github.material.monitor.demo.helper.PrivacyConsentStore;
import com.github.material.monitor.demo.mock.MockAdInfoFactory;
import com.github.material.monitor.demo.mock.MockAdTimingInput;

/**
 * 闪屏入口（对接文档 §3）。
 *
 * <p>流程：用户协议 → {@link MaterialMonitor#init} → 开屏容器 {@code collectFrameFromAdContainer}
 * → 进入 {@link MainActivity}。再次冷启动若已同意协议则跳过弹框。</p>
 */
public final class FirstActivity extends Activity {

    /** 闪屏停留时长，保证截帧 delay 能执行 */
    private static final long SPLASH_STAY_MS = 5000L;
    /** 开屏 delayMs，对接文档 §4.2 非激励约 2000ms */
    private static final long SPLASH_COLLECT_DELAY_MS = 2000L;

    private final Handler mainHandler = new Handler(Looper.getMainLooper());
    private FrameCallback frameCallback;
    private View splashContainer;
    private boolean flowStarted;

    private final Runnable openMainRunnable = new Runnable() {
        @Override
        public void run() {
            openMainAndFinish();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_first);
        splashContainer = findViewById(R.id.mock_splash_container);
        frameCallback = MaterialMonitorHelper.demoFrameCallback(this);

        if (PrivacyConsentStore.isAgreed(this)) {
            startSplashFlow();
        } else {
            showPrivacyDialog();
        }
    }

    /** 用户同意隐私后 init；可多次调用 init, 支持MonitorConfig热更（对接文档 §5.1） */
    private void initMonitor() {
        MaterialMonitor.init(getApplication(), DemoMonitorConfig.build());
    }

    private void showPrivacyDialog() {
        new AlertDialog.Builder(this)
                .setTitle(R.string.privacy_dialog_title)
                .setMessage(R.string.privacy_dialog_message)
                .setCancelable(false)
                .setNegativeButton(R.string.privacy_dialog_disagree, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                })
                .setPositiveButton(R.string.privacy_dialog_agree, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        PrivacyConsentStore.setAgreed(FirstActivity.this);
                        startSplashFlow();
                    }
                })
                .show();
    }

    private void startSplashFlow() {
        if (flowStarted) {
            return;
        }
        flowStarted = true;

        initMonitor();

        MaterialMonitorHelper.collectFrameFromAdPage(
                com.github.material.monitor.demo.FirstActivity.this,
                MockAdInfoFactory.forStyle(MaterialStyle.SPLASH),
                MockAdTimingInput.now(),
                SPLASH_COLLECT_DELAY_MS,
                frameCallback
        );

        mainHandler.postDelayed(openMainRunnable, SPLASH_STAY_MS);
    }

    private void openMainAndFinish() {
        if (isFinishing()) {
            return;
        }
        startActivity(new Intent(this, MainActivity.class));
        finish();
    }

    @Override
    protected void onDestroy() {
        mainHandler.removeCallbacks(openMainRunnable);
        super.onDestroy();
    }
}
