#include "lib/ringbuf.h"

#include <drivers/pty/pty.h>

#include <lib/print.h>

uint32_t pty_master_read(struct vfs_node* node, uint32_t offset, uint32_t size, uint8_t* buffer) {
    pty_t* pty = (pty_t*)node->data;
    uint32_t bytes_read = 0;
    while (bytes_read < size) {
        char c;
        if (ring_buf_read(&pty->slave_rb, &c) == 0) {
            buffer[bytes_read++] = c;
        } else {
            break;
        }
    }
    return bytes_read;
}

uint32_t pty_master_write(struct vfs_node* node, uint32_t offset, uint32_t size, uint8_t* buffer) {
    pty_t* pty = (pty_t*)node->data;
    uint32_t bytes_written = 0;

    while (bytes_written < size) {
        if (ring_buf_write(&pty->master_rb, buffer[bytes_written]) == 0) {
            bytes_written++;
            ring_buf_write(&pty->slave_rb, buffer[bytes_written-1]);
        } else {
            break;
        }
    }
    return bytes_written;
}

uint32_t pty_slave_read(struct vfs_node* node, uint32_t offset, uint32_t size, uint8_t* buffer) {
    pty_t* pty = (pty_t*)node->data;
    uint32_t bytes_read = 0;

    while (bytes_read < size) {
        char c;
        if (ring_buf_read(&pty->master_rb, &c) == 0) {
            buffer[bytes_read++] = c;
        } else {
            break;
        }
    }

    return bytes_read;
}

uint32_t pty_slave_write(struct vfs_node* node, uint32_t offset, uint32_t size, uint8_t* buffer) {
    pty_t* pty = (pty_t*)node->data;
    uint32_t bytes_written = 0;

    while (bytes_written < size) {
        if (ring_buf_write(&pty->slave_rb, buffer[bytes_written]) == 0) {
            bytes_written++;
        } else {
            break;
        }
    }

    return bytes_written;
}