package com.alterdekim.game.message.serializer;

import com.alterdekim.game.message.SerializerUtils;
import com.alterdekim.game.utils.ByteUtils;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class BinaryMessageSerializer {
    public static Integer deserializeInteger(List<Byte> bytes) {
        int value = 0;
        for (int i = 0; i < bytes.size(); i++) {
            value = (value << 8) + (bytes.get(i) & 0xFF);
        }
        return value;
    }

    public static Integer deserializeInteger(byte[] bytes) {
        assert bytes.length == 4;
        int value = 0;
        for (int i = 0; i < bytes.length; i++) {
            value = (value << 8) + (bytes[i] & 0xFF);
        }
        return value;
    }

    public static Long deserializeLong(List<Byte> bytes) {
        assert bytes.size() == 8;
        long value = 0;
        for (int i = 0; i < bytes.size(); i++) {
            value = (value << 8) + (bytes.get(i) & 0xFF);
        }
        return value;
    }

    public static Long deserializeLongUnsafe(List<Byte> bytes) {
        long value = 0;
        for (int i = 0; i < bytes.size(); i++) {
            value = (value << 8) + (bytes.get(i) & 0xFF);
        }
        return value;
    }

    public static Long deserializeLong(byte[] bytes) {
        assert bytes.length == 8;
        long value = 0;
        for (int i = 0; i < bytes.length; i++) {
            value = (value << 8) + (bytes[i] & 0xFF);
        }
        return value;
    }

    public static List<Byte> serializeInteger(Integer i) {
        return serializeNumber(i.doubleValue());
    }

    private static List<Byte> serializeLong(Long l) {
        return serializeNumber(l.doubleValue());
    }

    private static List<Byte> serializeDouble(Double d) {
        return serializeNumber(d);
    }

    private static List<Byte> serializeFloat(Float f) {
        return serializeNumber(f.doubleValue());
    }

    private static List<Byte> serializeNumber(Double d) {
        return SerializerUtils.primitiveToBytes(ByteUtils.longToBytes(Double.doubleToLongBits(d)));
    }
}
