/*
 * wnix, a Unix-like operating system for WebAssembly applications.
 * Copyright (C) 2025  Xavier Del Campo Romero
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

#include <drv/ps1/cd/routines.h>
#include <drv/ps1/bios.h>
#include <drv/ps1/event.h>
#include <kprintf.h>

static int wait_event(void)
{
    struct cd_prv *const p = &drv_ps1_cd_prv;
    struct cd_prv_getstat *const g = &p->u.getstat;

    p->available = true;
    p->next = NULL;
    return 0;

    if (drv_ps1_event_test(p->event))
    {
        p->available = !g->status.bits.shell_open;

        if (!p->head)
            return 0;

        return p->head->f();
    }

    return 0;
}

static int ensure_event(struct cd_prv *const p)
{
    if (p->event)
        return 0;
    else if ((p->event = drv_ps1_event_open(CLASS_CDROM, SPEC_COMMAND_COMPLETE,
        MODE_READY, NULL)) == -1)
        return -1;

    drv_ps1_event_enable(p->event);
    return 0;
}

int drv_ps1_cd_getstat(void)
{
    struct cd_prv *const p = &drv_ps1_cd_prv;
    struct cd_prv_getstat *const g = &p->u.getstat;

    /* TODO: CdAsyncGetStatus is *very* slow (~2.5 seconds / 10k calls) */
    if (ensure_event(p))
        return -1;
    else if (!CdAsyncGetStatus(&g->status.byte))
    {
        kprintf("%s: CdAsyncGetStatus failed\n", __func__);
        return -1;
    }

    p->next = wait_event;
    return 0;
}
