/*
 * 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.h>
#include <drv/ps1/cd/types.h>
#include <drv/ps1/cd/routines.h>
#include <drv/event.h>
#include <stdbool.h>

int drv_ps1_cd_update(struct drv_ps1_cd *const cd)
{
    struct cd_prv *const p = &drv_ps1_cd_prv;

    if (!p->next && p->head)
        return p->head->f();
    if (p->next && p->next())
        return -1;
    else if (p->available ^ cd->available)
    {
        const struct drv_event *const ev = &cd->ev;
        static const struct drv_event_ops ops =
        {
            .read = drv_ps1_cd_read,
            .write = drv_ps1_cd_write
        };

        if (ev->status("cd0", &ops, p->available, 0440, ev->args))
            return -1;

        cd->available = p->available;
    }

    return 0;
}
