#include "iso.h"

#include "drivers/ide/ide.h"

#include "lib/print.h"
#include "lib/memory.h"

uint8_t sector_buf[2048];
void read_iso(ide_device_t* dev) {
    int success = ide_read_blks(dev, 16, 1, sector_buf);
    if (!success) {
        kprintf("Failed to read PVD\n");
        return;
    }

    if (sector_buf[0] != 1) {
        kprintf("Couldn't find PVD in sector 0x10\n");
        return;
    }

    iso_pvd_t* pvd = (iso_pvd_t*)sector_buf;

    char pvd_identifier[6];
    memcpy(pvd->header.identifier, pvd_identifier, 5);
    pvd_identifier[5] = 0;

    if (strcmp(pvd_identifier, "CD001") > 0) {
        kprintf("Invalid PVD identifier\n");
        return;
    }

    char volume_identifier[33];
    memset((uint8_t*)volume_identifier, 0, 33);
    memcpy(&pvd->volume_ident[0], volume_identifier, 32);

    kprintf("Reading ISO Filesystem from CDROM Disk %s\n", volume_identifier);

    uint32_t lba_path_table = pvd->path_table_l_loc;
    uint32_t path_table_sz = pvd->path_table_sz_le;
    uint32_t sectors = path_table_sz / 2048;
    if (sectors % 2048 > 0 || sectors == 0) {
        sectors++;
    }

    uint8_t path_table_sec[2048 * sectors];
    memset(path_table_sec, 0, 2048);
    success = ide_read_blks(dev, lba_path_table, 1, path_table_sec);
    if (!success) {
        kprintf("could not read path table at lba 0x%x\n", lba_path_table);
        return;
    }

    iso_path_table_entry_t* path = (iso_path_table_entry_t*)path_table_sec;
    while ((uint32_t)path - (uint32_t)path_table_sec < 2048) {
        size_t entry_sz = sizeof(iso_path_table_entry_t) + (path->dir_ident_len - 1);
        if (path->dir_ident_len % 2 > 0) entry_sz++;
        path = (iso_path_table_entry_t*)((uint32_t)path + entry_sz);
    }
}