package com.github.material.monitor.demo;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;

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.MaterialMonitorHelper;
import com.github.material.monitor.demo.mock.MockAdActivity;
import com.github.material.monitor.demo.mock.MockAdInfo;
import com.github.material.monitor.demo.mock.MockAdInfoFactory;
import com.github.material.monitor.demo.mock.MockAdTimingInput;
import com.github.material.monitor.demo.mock.MockGalleryActivity;

/**
 * 各广告样式接入演示（对接文档 §4、§5）。
 *
 * <ul>
 *   <li>Banner / 原生：{@code collectFrameFromAdContainer} / {@code collectFrameFromNativeAdContainer}</li>
 *   <li>插屏 / 激励：{@code collectFrameFromAdPage} + 第三方 {@link MockAdActivity}</li>
 * </ul>
 */
public final class MainActivity extends Activity implements View.OnClickListener {

    private static final int REQUEST_MOCK_AD = 1001;

    /** 激励 delayMs 下限，对接文档 §4.2 建议 2～5 秒 */
    private static final long REWARDED_MIN_COLLECT_DELAY_MS = 3000L;
    private static final long INTERSTITIAL_MIN_DISPLAY_MS = 4000L;
    private static final long REWARDED_MIN_DISPLAY_MS = 7000L;

    /**
     * 图片类原生自渲染素材 url-only 示例 URL（§4.4）。正式接入传 {@code getAdMaterial().getMainImageUrl()} 等。
     */
    private static final String DEMO_NATIVE_IMAGE_URL = "";

    private EditText delayInput;
    private FrameCallback frameCallback;

    private View mockBanner;
    private View mockNative;

    /** 当前插屏 / 激励的 MockAdInfo，供 mock 页关闭时在宿主页调用 onAdClosed */
    private MockAdInfo pendingFullScreenAdInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        frameCallback = MaterialMonitorHelper.demoFrameCallback(this);

        delayInput = findViewById(R.id.et_delay);
        mockBanner = findViewById(R.id.mock_banner);
        mockNative = findViewById(R.id.mock_native);

        findViewById(R.id.btn_frame_banner).setOnClickListener(this);
        findViewById(R.id.btn_show_interstitial).setOnClickListener(this);
        findViewById(R.id.btn_show_rewarded).setOnClickListener(this);
        findViewById(R.id.btn_frame_native).setOnClickListener(this);
        findViewById(R.id.btn_frame_native_url).setOnClickListener(this);
        findViewById(R.id.btn_flush).setOnClickListener(this);
        findViewById(R.id.btn_open_gallery).setOnClickListener(this);
    }

    /**
     * 回到前台时尝试发送离线队列（对接文档 §5.7 flushPendingFrames）。
     */
    @Override
    protected void onResume() {
        super.onResume();
        MaterialMonitor.get().flushPendingFrames();
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.btn_flush) {
            MaterialMonitor.get().flushPendingFrames();
            return;
        }
        if (id == R.id.btn_open_gallery) {
            startActivity(new Intent(this, MockGalleryActivity.class));
            return;
        }

        long delayMs = getDelayMs();
        if (id == R.id.btn_frame_banner) {
            collectFromContainer(mockBanner, MaterialStyle.BANNER, delayMs);
        } else if (id == R.id.btn_show_interstitial) {
            showFullScreenAd(MaterialStyle.INTERSTITIAL, delayMs);
        } else if (id == R.id.btn_show_rewarded) {
            showFullScreenAd(MaterialStyle.REWARDED_VIDEO, delayMs);
        } else if (id == R.id.btn_frame_native) {
            // 原生模版或原生视频类素材
            collectFromContainer(mockNative, MaterialStyle.NATIVE, delayMs);
        } else if (id == R.id.btn_frame_native_url) {
            // 图片类原生自渲染广告素材：有效 URL 时走 url-only（§4.4 / §5.3）
            MaterialMonitorHelper.collectFrameFromNativeAdContainer(
                    mockNative,
                    MockAdInfoFactory.forStyle(MaterialStyle.NATIVE),
                    MockAdTimingInput.now(),
                    DEMO_NATIVE_IMAGE_URL,
                    delayMs,
                    frameCallback
            );
        }
    }

    /**
     * mock 第三方全屏页关闭：在<b>宿主页</b>调用 onAdClosed（§5.5），取消尚未执行的延时截帧。
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_MOCK_AD && pendingFullScreenAdInfo != null) {
            MaterialMonitorHelper.onAdClosed(pendingFullScreenAdInfo);
            pendingFullScreenAdInfo = null;
        }
    }

    private void collectFromContainer(View target, MaterialStyle style, long delayMs) {
        MaterialMonitorHelper.collectFrameFromAdContainer(
                target,
                MockAdInfoFactory.forStyle(style),
                MockAdTimingInput.now(),
                delayMs,
                frameCallback
        );
    }

    /**
     * 插屏 / 激励标准流程（§5.4）：
     * 1. 宿主页 collectFrameFromAdPage
     * 2. 打开第三方全屏 Activity
     * 3. delayMs 后 SDK 截取前台 resumed Activity
     * 4. 广告关闭时宿主页 onAdClosed
     */
    private void showFullScreenAd(MaterialStyle style, long delayMs) {
        long collectDelayMs = delayMs;
        if (style == MaterialStyle.REWARDED_VIDEO && collectDelayMs < REWARDED_MIN_COLLECT_DELAY_MS) {
            collectDelayMs = REWARDED_MIN_COLLECT_DELAY_MS;
        }

        pendingFullScreenAdInfo = MockAdInfoFactory.forStyle(style);
        MaterialMonitorHelper.collectFrameFromAdPage(
                MainActivity.this,
                pendingFullScreenAdInfo,
                MockAdTimingInput.now(),
                collectDelayMs,
                frameCallback
        );

        long displayMs = computeDisplayMs(style, collectDelayMs);
        startActivityForResult(MockAdActivity.buildIntent(this, style, displayMs), REQUEST_MOCK_AD);
    }

    private static long computeDisplayMs(MaterialStyle style, long collectDelayMs) {
        if (style == MaterialStyle.REWARDED_VIDEO) {
            return Math.max(collectDelayMs + 3000L, REWARDED_MIN_DISPLAY_MS);
        }
        return Math.max(collectDelayMs + 2000L, INTERSTITIAL_MIN_DISPLAY_MS);
    }

    private long getDelayMs() {
        String text = delayInput.getText() == null ? "" : delayInput.getText().toString();
        if (TextUtils.isEmpty(text)) {
            return 2000L;
        }
        try {
            return Math.max(0L, Long.parseLong(text));
        } catch (Throwable ignore) {
            return 2000L;
        }
    }
}
