import datetime

from src.internals.serializers import unsafe_dumper, unsafe_loader


def serialize_dms(dms, dumper=unsafe_dumper):
    return dumper(dms)


def deserialize_dms(dms_str, loader=unsafe_loader):
    dms = loader(dms_str)
    for element in dms:
        rebuild_dm_fields(element)
    return dms


def rebuild_dm_fields(dm):
    dm["added"] = datetime.datetime.fromisoformat(dm["added"])
    dm["published"] = datetime.datetime.fromisoformat(dm["published"])
    if dm.get("deleted_at"):
        dm["deleted_at"] = datetime.datetime.fromisoformat(dm["deleted_at"])
    return dm


def prepare_dm_fields(dm):
    dm["added"] = dm["added"].isoformat()
    dm["published"] = dm["published"].isoformat()
    if dm.get("deleted_at"):
        dm["deleted_at"] = dm["deleted_at"].isoformat()
    return dm
