#include "core/utils/Random.hpp"

#include <stdio.h>

constexpr static int M = 7;

Core::Random::Random(Seed seed) : data(), index(0) {
    for(size_t i = 0; i < data.getLength(); i++) {
        data[i] = seed;
        seed = seed * 7 + 31;
    }
}

void Core::Random::update() {
    static const Seed map[2] = {0, 0x8EBFD028};
    for(size_t i = 0; i < data.getLength() - M; i++) {
        data[i] = data[i + M] ^ (data[i] >> 1) ^ map[data[i] & 1];
    }
    for(size_t i = data.getLength() - M; i < data.getLength(); i++) {
        data[i] = data[i + (M - data.getLength())] ^ (data[i] >> 1) ^
                  map[data[i] & 1];
    }
    index = 0;
}

Core::Random::Seed Core::Random::next() {
    if(index >= data.getLength()) {
        update();
    }
    Seed r = data[index++];
    r ^= (r << 7) & 0x2B5B2500;
    r ^= (r << 15) & 0xDB8B0000;
    r ^= (r >> 16);
    return r;
}

template<typename T>
T limit(T value, T min, T inclusiveMax) {
    return min + value % (inclusiveMax - min + 1);
}

Core::Random::Seed Core::Random::next(Seed min, Seed inclusiveMax) {
    return limit(next(), min, inclusiveMax);
}

i32 Core::Random::nextI32() {
    return static_cast<i32>(next() >> 1);
}

i32 Core::Random::nextI32(i32 min, i32 inclusiveMax) {
    return limit(nextI32(), min, inclusiveMax);
}

size_t Core::Random::nextSize() {
    if constexpr(sizeof(size_t) <= sizeof(Seed)) {
        return static_cast<size_t>(next());
    } else {
        return static_cast<size_t>(next()) |
               (static_cast<size_t>(next()) >> 32);
    }
}

size_t Core::Random::nextSize(size_t min, size_t inclusiveMax) {
    return limit(nextSize(), min, inclusiveMax);
}

bool Core::Random::nextBool() {
    return next() & 1;
}

float Core::Random::nextFloat() {
    static constexpr i32 m = 0x7FFFFFFF;
    float f = static_cast<float>(next() & m) * (1.0f / static_cast<float>(m));
    return f >= 1.0f ? nextFloat() : f;
}

float Core::Random::nextFloat(float min, float exclusiveMax) {
    return min + nextFloat() * (exclusiveMax - min);
}