/* SPDX-License-Identifier: GPL-3.0-or-later */
/* Mission Announcer. Select ssc, input and bcontrol in Project Settings. */
#include <cmoc.h>
#include <coco.h>
#include <vcc/input.h>
#include <vcc/ssc.h>

#define VOICE_SLOT 1
#define ALERT_SLOT 2
#define MESSAGE_SLOT 3
#define POLL_LIMIT 30000

/* Z + "or" + an unstressed vowel: give our invented planet a voice. */
static const unsigned char zora[] = { SSC_AL_ZZ, SSC_AL_OR, SSC_AL_AX };

int main(void)
{
    unsigned int route, lastSample, now, landings = 0;
    unsigned char key, status;
    VccInput stick;

    cls(1);
    printf("MISSION ANNOUNCER\n");
    route = ssc_route_audio();
    /* Store each recipe once. The two slot numbers belong to separate banks. */
    status = ssc_store_allophones(VOICE_SLOT, zora, sizeof(zora), POLL_LIMIT);
    if (status == SSC_OK)
        status = ssc_store_phrase(MESSAGE_SLOT, "WELCOME ABOARD", POLL_LIMIT);
    if (status == SSC_OK)
        status = ssc_store_enveloped_tone(ALERT_SLOT, 0, 420, SSC_ENV_DECAY,
                                          1800, 18, POLL_LIMIT);
    if (status == SSC_OK) {
        input_init(&stick, INPUT_RIGHT);
        lastSample = getTimer();
        printf("1  ANNOUNCE ZORA\n2  CREW MESSAGE\nFIRE  LANDING ALERT\nQ  RETURN TO BASIC\n");
        while (status == SSC_OK) {
            key = inkey();
            if (key == 'Q' || key == 'q')
                break;
            if (key == '1') {
                status = ssc_play_allophones(VOICE_SLOT, POLL_LIMIT);
                if (status == SSC_OK)
                    printf("APPROACHING ZORA\n");
            } else if (key == '2') {
                status = ssc_play_phrase(MESSAGE_SLOT, POLL_LIMIT);
                if (status == SSC_OK)
                    printf("WELCOME ABOARD\n");
            }
            /* Joystick readings share the audio mux. Sample once per guest tick. */
            now = getTimer();
            if (now == lastSample)
                continue;
            lastSample = now;
            input_sample(&stick);
            /* A press is an edge: holding the button counts as one landing. */
            if (status == SSC_OK && (stick.pressed & INPUT_PRIMARY)) {
                status = ssc_play_stored_effect(ALERT_SLOT, POLL_LIMIT);
                if (status == SSC_OK)
                    printf("LANDING ALERT %u\n", ++landings);
            }
        }
    }
    /* A partial command may remain after timeout. Reset only on that path. */
    if (status == SSC_TIMEOUT)
        ssc_reset();
    ssc_restore_audio(route);
    if (status != SSC_OK)
        printf("CHECK CARTRIDGE AND FIRMWARE\n");
    return status;
}
