# naughty.games SDK for Ren'Py 8 web builds (SDK v1): lifecycle and ad breaks.
# Guide: https://naughty.games/guides/in-game-ads-sdk
#
# Setup: put this file in your project's game/ folder. That's all.
#
# When the page has no window.NgSdk, this file adds the SDK script tag itself
# (once) and waits for it to load. Optional: add
#   <script src="https://naughty.games/sdk/v1.js"></script>
# inside <head> of web/index.html in your Ren'Py SDK folder. Every web build
# copies that file, the SDK loads a little earlier, and the developer console
# says "SDK detected" at upload time. Updating Ren'Py replaces the file, so
# add the tag again after an update.
#
# Use, from a label or a $ line in your script:
#   $ ng_sdk.commercial_break()    # between chapters, never mid-scene
#
#   menu:
#       "Watch an ad for a hint" if ng_sdk.ads_enabled():
#           $ granted = ng_sdk.rewarded_break()
#           if granted:
#               "The key is under the mat."
#           else:
#               "No ad right now. Try again later."
#
# From a screen button, wrap it in your own function:
#   init python:
#       def watch_ad_for_gems():
#           if ng_sdk.rewarded_break():
#               store.gems += 50
#   textbutton "Watch an ad for 50 gems" action Function(watch_ad_for_gems)
#
# The wrapper calls NgSdk.init() and gameLoadingFinished() when the game
# starts. While an ad plays, the script waits and every audio channel is
# paused, then resumed; a channel you had paused yourself stays paused. Off
# the web (desktop, Android, the Launcher) every break returns at once and
# rewarded_break() returns False.
#
# Rules: grant a reward only when rewarded_break() returns True. A break can
# finish at once (no ad available, too soon after the last one, or another
# break still running), so the story always carries on after the call.

init -10 python in ng_sdk:

    import time
    import store

    ## Pause every audio channel while an ad plays. Set it to False with
    ## define ng_sdk.pause_audio = False if you silence audio yourself.
    pause_audio = True

    ## Give up waiting after this many seconds. The SDK itself always settles
    ## sooner; this only guards against a page that never answers.
    max_wait = 150.0

    # The page side lives on window.ngRenpy, not in the store, so nothing
    # here is saved or rolled back. When the page has no window.NgSdk yet,
    # it adds the SDK script tag itself (once) and waits for it to load.
    _SETUP_JS = r"""
    (function () {
        if (window.ngRenpy) return;
        var s = window.ngRenpy = {
            env: "inert", token: 0, busy: 0, done: 1, granted: 0, muted: 0, sdk: null, waiting: []
        };
        s.use = function (fn) {
            if (s.waiting) s.waiting.push(fn);
            else fn(s.sdk);
        };
        var timer = null;
        function connect() {
            if (!s.waiting) return;
            clearTimeout(timer);
            var sdk = s.sdk = window.NgSdk || null;
            if (sdk) {
                sdk.on("mute", function () { s.muted = 1; });
                sdk.on("unmute", function () { s.muted = 0; });
                sdk.init().then(function (r) { s.env = String((r && r.env) || "inert"); }, function () {});
            } else {
                console.warn("[naughty.games SDK] could not load https://naughty.games/sdk/v1.js. Breaks finish at once.");
            }
            var queue = s.waiting;
            s.waiting = null;
            for (var i = 0; i < queue.length; i++) queue[i](sdk);
        }
        if (window.NgSdk) return connect();
        // Give up on a script that neither loads nor fails after 10 seconds.
        timer = setTimeout(connect, 10000);
        try {
            var tag = document.createElement("script");
            tag.src = "https://naughty.games/sdk/v1.js";
            tag.addEventListener("load", connect);
            tag.addEventListener("error", connect);
            (document.head || document.documentElement).appendChild(tag);
        } catch (e) {
            connect();
        }
    })();
    """

    # Returns 1 when the break started, 0 when another one is still running.
    _BREAK_JS = r"""
    (function (s, kind) {
        if (s.busy) return 0;
        var t = ++s.token;
        s.busy = 1;
        s.done = 0;
        s.granted = 0;
        function end(ok) {
            if (s.token !== t) return;
            s.granted = ok ? 1 : 0;
            s.done = 1;
        }
        s.use(function (sdk) {
            if (!sdk) return end(false);
            try {
                var p = kind === "rewarded" ? sdk.rewardedBreak() : sdk.commercialBreak();
                p.then(function (v) { end(kind === "rewarded" && v === true); }, function () { end(false); });
            } catch (e) {
                end(false);
            }
        });
        return 1;
    })(window.ngRenpy, "%s")
    """

    _STATE_JS = "(function (s) { return s.done | (s.granted << 1) | (s.muted << 2); })(window.ngRenpy)"

    def _web():
        return bool(renpy.emscripten)

    def _setup():
        if _web():
            renpy.emscripten.run_script(_SETUP_JS)
        return _web()

    def _call(method):
        if _setup():
            renpy.emscripten.run_script(
                "window.ngRenpy.use(function (sdk) { if (sdk) sdk.%s(); });" % method)

    def env():
        """
        "naughty" on naughty.games, "local" in test mode (localhost or
        ?ngsdk=test), "inert" anywhere else, including desktop builds.
        """
        if not _setup():
            return "inert"
        return renpy.emscripten.run_script_string("String(window.ngRenpy.env)")

    def ads_enabled():
        """
        True where a break can show an ad. Use it to hide "watch an ad"
        choices on desktop builds and on other sites.
        """
        return env() in ("naughty", "local")

    def game_loading_finished():
        _call("gameLoadingFinished")

    def gameplay_start():
        _call("gameplayStart")

    def gameplay_stop():
        _call("gameplayStop")

    def _channels():
        # Every registered channel once, by name ("audio 0" and the like
        # included), without the numbered aliases.
        try:
            return [ c.name for c in renpy.audio.audio.all_channels ]
        except Exception:
            return [ "music", "sound", "voice" ]

    def _pause_channels():
        paused = [ ]
        for name in _channels():
            try:
                if not renpy.music.get_pause(channel=name):
                    renpy.music.set_pause(True, channel=name)
                    paused.append(name)
            except Exception:
                pass
        return paused

    def _resume_channels(paused):
        for name in paused:
            try:
                renpy.music.set_pause(False, channel=name)
            except Exception:
                pass

    def _wait_a_moment():
        # Like renpy.fetch: inside an interaction (a screen action) keep the
        # audio serviced and hand the browser a turn; outside one, show a frame.
        if renpy.game.context().interacting or store.config.skipping == "fast":
            renpy.pygame_sdl2.event.pump()
            renpy.audio.audio.periodic()
            renpy.emscripten.sleep(50)
        else:
            renpy.pause(0)

    def _run_break(kind):
        if not _setup():
            return False
        if not renpy.emscripten.run_script_int(_BREAK_JS % kind):
            # Another break is still running: this one finishes at once.
            return False
        paused = None
        deadline = time.time() + max_wait
        try:
            while True:
                state = renpy.emscripten.run_script_int(_STATE_JS)
                if pause_audio:
                    if state & 4 and paused is None:
                        paused = _pause_channels()
                    elif not state & 4 and paused is not None:
                        _resume_channels(paused)
                        paused = None
                if state & 1:
                    return bool(state & 2)
                if time.time() > deadline:
                    return False
                _wait_a_moment()
        finally:
            renpy.emscripten.run_script("window.ngRenpy.busy = 0;")
            if paused is not None:
                _resume_channels(paused)

    def commercial_break():
        """
        Shows an ad if one is due, then returns. Often returns at once.
        """
        _run_break("commercial")

    def rewarded_break():
        """
        Offers a rewarded ad. Returns True only when the player watched it to
        the end.
        """
        return _run_break("rewarded")

    def _on_start():
        game_loading_finished()

    store.config.start_callbacks.append(_on_start)
