// SPDX-License-Identifier: GPL-3.0-or-later
// The card holds disk images. Each planet disk holds its own LANDING.TXT.
#include <coco.h>
#include <stdio.h>
#include <vcc/sdc.h>

// Browse the card once. A directory entry describes the image file itself.
static void showChart(void)
{
    SdcEntry entry;
    unsigned char result = sdc_list_begin("/*.DSK");
    printf("DISKS ON THE PRACTICE CARD\n");
    if (result == SDC_OK)
        while ((result = sdc_list_next(&entry)) == SDC_OK)
            if (!(entry.attributes & SDC_DIRECTORY))
                printf("  %s\n", entry.name);
    if (result != SDC_END)
        printf("CHART UNAVAILABLE (%u)\n", (unsigned)result);
}

// The controller reports the actual filename, even after a failed mount.
static void showDrive(unsigned char drive)
{
    SdcEntry entry;
    unsigned char result = sdc_mounted(drive, &entry);
    printf("SDC%u: ", (unsigned)drive);
    if (result == SDC_OK)
        printf("%s\n", entry.name);
    else if (result == SDC_NOT_FOUND)
        printf("EMPTY\n");
    else
        printf("CANNOT QUERY (%u)\n", (unsigned)result);
}

static void landingReport(void)
{
    // :1 asks the Disk BASIC ROM for a file inside the mounted planet.
    FILE *file = fopen("LANDING.TXT:1", "r");
    char line[40];
    int ok;
    if (!file)
    {
        printf("NO LANDING REPORT ON DRIVE 1\n");
        return;
    }
    while (fgets(line, sizeof(line), file))
        printf("%s", line);
    ok = !ferror(file);
    if (fclose(file) == EOF || !ok)
        printf("ERROR READING LANDING REPORT\n");
}

int main(void)
{
    int key;
    unsigned char result;
    const char *path;
    width(40);
    cls(1);
    printf("PLANET EXPEDITION\n\n");
    if (sdc_probe() != SDC_OK)
    {
        printf("CHOOSE THE COCO SDC PROFILE\n");
        return 1;
    }
    showChart();
    for (;;)
    {
        printf("\n");
        showDrive(0);
        showDrive(1);
        printf("\n1 EARTH    2 MARS\n3 TRY MISSING DISK    Q QUIT\n");
        do {
            key = waitkey(0);
        } while (key != '1' && key != '2' && key != '3' && key != 'Q' && key != 'q');
        if (key == 'Q' || key == 'q')
            break;

        // No file is open here. Leave drive 0 alone and change only drive 1.
        path = key == '1' ? "/EARTH.DSK" : key == '2' ? "/MARS.DSK" : "/MISSING.DSK";
        result = sdc_mount(1, path);
        cls(1);
        printf("PLANET EXPEDITION\n\n");
        if (result == SDC_OK)
            printf("LANDED\n");
        else
            printf("COULD NOT MOUNT %s (%u)\n", path, (unsigned)result);
        // Read what is actually mounted, including after a rejected change.
        landingReport();
    }
    printf("EXPEDITION COMPLETE\n");
    return 0;
}
