import copy
import datetime

from src.internals.serializers import unsafe_dumper, unsafe_loader


def serialize_dict(data, dumper=None):
    to_serialize = {"dates": [], "data": {}}

    for key, value in data.items():
        if isinstance(value, (datetime.datetime, datetime.date)):
            to_serialize["dates"].append(key)
            to_serialize["data"][key] = value.isoformat()
        else:
            to_serialize["data"][key] = value

    if dumper:
        return dumper(to_serialize)
    else:
        return to_serialize


def deserialize_dict(data, loader=None):
    if loader:
        data = loader(data)
    to_return = {}
    for key, value in data["data"].items():
        if key in data["dates"]:
            to_return[key] = datetime.datetime.fromisoformat(value)
        else:
            to_return[key] = value
    return to_return


def serialize_dict_list(data, serialize_method=unsafe_dumper):
    data = copy.deepcopy(data)
    return serialize_method([serialize_dict(elem) for elem in data])


def deserialize_dict_list(data, deserialize_method=unsafe_loader):
    data = deserialize_method(data)
    to_return = [deserialize_dict(elem) for elem in data]
    return to_return
