/*
    * BlockDevice.cpp
    * Driver-agnostic block device registry
    * Copyright (c) 2026 Daniel Hammer
*/

#include "BlockDevice.hpp"

namespace Drivers::Storage {

    static BlockDevice g_devices[MaxBlockDevices] = {};
    static bool g_active[MaxBlockDevices] = {};
    static int g_deviceHighWater = 0;

    int RegisterBlockDevice(const BlockDevice& dev) {
        for (int i = 0; i < MaxBlockDevices; i++) {
            if (g_active[i]) continue;

            g_devices[i] = dev;
            g_active[i] = true;
            if (i >= g_deviceHighWater) {
                g_deviceHighWater = i + 1;
            }
            return i;
        }

        return -1;
    }

    int UnregisterBlockDevice(int index) {
        if (index < 0 || index >= MaxBlockDevices || !g_active[index]) return -1;

        g_active[index] = false;
        g_devices[index] = {};

        while (g_deviceHighWater > 0 && !g_active[g_deviceHighWater - 1]) {
            g_deviceHighWater--;
        }

        return 0;
    }

    const BlockDevice* GetBlockDevice(int index) {
        if (index < 0 || index >= MaxBlockDevices || !g_active[index]) return nullptr;
        return &g_devices[index];
    }

    int GetBlockDeviceCount() {
        return g_deviceHighWater;
    }

};
