import pickle
import socket
import json


def read_json_config(filename: str):
    with open(filename, 'r') as file:
        return json.loads(file.read())


TCP_CHUNK_SIZE = 16384


class SocketBlocksWrapper:
    def __init__(self, s, address: str = None, port: int = None):
        self.sock = s

    def get_socket(self):
        return self.sock

    def _read_block(self):
        arr = self.sock.recv(8)
        if len(arr) < 8:
            return None
        data_size = int.from_bytes(arr, 'little')

        # далее нужно читать данные чанками, потому что в противном случае будет говно
        received_size = 0
        data = bytearray()
        while received_size < data_size:
            to_recv = data_size - received_size
            if to_recv > TCP_CHUNK_SIZE:
                to_recv = TCP_CHUNK_SIZE
            r = self.sock.recv(to_recv)
            if len(r) == 0:
                continue
            received_size += len(r)
            data += r
        return data

    def read_object(self):
        raw = self._read_block()
        if raw is None:
            return None
        return pickle.loads(raw)

    def _write_block(self, data: bytes):
        data_size = len(data).to_bytes(8, 'little')
        to_send = bytearray(data_size)
        to_send += data
        # print(f"libstreamer: write {len(to_send)} bytes")
        self.sock.send(to_send)

    def write_object(self, obj):
        to_send = pickle.dumps(obj)
        self._write_block(to_send)

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.sock.close()

    @staticmethod
    def connect(host: str, port: int):
        sock = socket.socket()
        sock.connect((host, port))
        return SocketBlocksWrapper(sock)


