/*
 * 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 <aio.h>
#include <fs/fs.h>
#include <aio/types.h>
#include <state.h>
#include <errno.h>
#include <stddef.h>
#include <stdlib.h>

struct open
{
    struct aio *aio;
    struct fs_open open;
    struct aio_done done;
};

static int done(const enum state s, void *const args)
{
    struct open *const o = args;
    const struct aio_done *const d = &o->done;

    if (d->f)
        d->f(s, d->args);

    free(o);
    return 0;
}

static enum state opened(void *const args)
{
    return STATE_OK;
}

static int search_done(const enum state state, const char *const relpath,
    const struct fs_mp *const mp, const union inode_result *const inode,
    void *const args)
{
    struct open *const o = args;
    struct aio *const aio = o->aio;
    const struct fs *const fs = mp->fs;

    if (!inode)
    {
        aio->error = ENOENT;
        goto failure;
    }

    aio->r = (const struct fs_ret)
    {
        .f = opened,
        .args = o
    };

    if (fs->open(&o->open, mp, inode, &aio->r))
    {
        aio->error = errno;
        goto failure;
    }

    return 0;

failure:
    aio->done = o->done;
    free(o);
    return -1;
}

struct aio *aio_open(const struct fs_open *const op,
    const struct aio_done *const d)
{
    struct aio *aio = NULL;
    struct open *const o = malloc(sizeof *o);

    if (!o || !(aio = malloc(sizeof *aio)))
        goto failure;

    *o = (const struct open)
    {
        .aio = aio,
        .open = *op
    };

    *aio = (const struct aio)
    {
        .done =
        {
            .f = done,
            .args = o
        }
    };

    const struct inode_search s =
    {
        .path = op->path,
        .done = search_done,
        .args = o
    };

    if (inode_search(&s, &aio->r))
        goto failure;
    else if (d)
        o->done = *d;

    return aio;

failure:
    free(aio);
    return NULL;
}
