#include "data/BitArray.h"
#include "math/Math.h"

static int roundUpDivide(int a, int b) {
    if(a % b == 0) {
        return a / b;
    }
    return a / b + 1;
}

static constexpr int INT_BITS = sizeof(int) * 8;
static constexpr int DIVIDE_BITS = Math::roundUpLog2(INT_BITS);

static int readBits(const int* data, int index, int bits) {
    int dataIndexA = (index * bits) >> DIVIDE_BITS;
    int dataIndexB = ((index + 1) * bits) >> DIVIDE_BITS;
    int shifts = (index * bits) & (INT_BITS - 1);
    if(dataIndexA == dataIndexB) {
        return (data[dataIndexA] >> shifts) & ((1 << bits) - 1);
    }
    int bitsInA = INT_BITS - shifts;
    int r = (data[dataIndexA] >> shifts) & ((1 << bitsInA) - 1);
    r |= (data[dataIndexB] & ((1 << (bits - bitsInA)) - 1)) << bitsInA;
    return r;
}

static void setBits(int* data, int index, int bits, int value) {
    int mask = (1 << bits) - 1;
    value &= mask;
    int dataIndexA = (index * bits) >> DIVIDE_BITS;
    int dataIndexB = ((index + 1) * bits) >> DIVIDE_BITS;
    int shifts = (index * bits) & (INT_BITS - 1);
    data[dataIndexA] &= ~(mask << shifts);
    data[dataIndexA] |= (value << shifts);
    if(dataIndexA != dataIndexB) {
        int leftBits = bits - (INT_BITS - shifts);
        int mask = (1 << leftBits) - 1;
        data[dataIndexB] &= ~mask;
        data[dataIndexB] |= (value >> (INT_BITS - shifts));
    }
}

BitArray::BitArray(int length, int bits)
    : length(length), bits(bits),
      data(new int[roundUpDivide(length * bits, sizeof(int))]) {
}

BitArray::BitArray(const BitArray& other) : BitArray(other.length, other.bits) {
    for(int i = 0; i < length; i++) {
        set(i, other.get(i));
    }
}

BitArray::BitArray(BitArray&& other) : length(0), bits(0), data(nullptr) {
    swap(other);
}

BitArray::~BitArray() {
    delete[] data;
}

BitArray& BitArray::operator=(BitArray other) {
    swap(other);
    return *this;
}

BitArray& BitArray::set(int index, int value) {
    setBits(data, index, bits, value);
    return *this;
}

int BitArray::get(int index) const {
    return readBits(data, index, bits);
}

int BitArray::getLength() const {
    return length;
}

int BitArray::getBits() const {
    return bits;
}

void BitArray::fill(int value) {
    for(int i = 0; i < length; i++) {
        set(i, value);
    }
}

void BitArray::resize(int newBits) {
    int* newData = new int[roundUpDivide(length * newBits, sizeof(int))];
    for(int i = 0; i < length; i++) {
        setBits(newData, i, newBits, get(i));
    }
    delete[] data;
    data = newData;
    bits = newBits;
}

void BitArray::swap(BitArray& other) {
    std::swap(length, other.length);
    std::swap(bits, other.bits);
    std::swap(data, other.data);
}