import datetime

from src.internals.serializers import unsafe_dumper, unsafe_loader


def serialize_post(data, dumper=unsafe_dumper):
    return dumper(data)


def deserialize_post(data, loader=unsafe_loader):
    return rebuild_post_fields(loader(data))


def serialize_post_list(data, dumper=unsafe_dumper):
    return dumper(data)


def deserialize_post_list(data, loader=unsafe_loader):
    posts = loader(data)
    for element in posts:
        rebuild_post_fields(element)
    return posts


def serialize_posts_incomplete_rewards(posts_incomplete_rewards, dumper=unsafe_dumper):
    return dumper(posts_incomplete_rewards)


def deserialize_posts_incomplete_rewards(posts_incomplete_rewards_str, loader=unsafe_loader):
    obj = loader(posts_incomplete_rewards_str)
    if obj:
        obj["last_checked_at"] = datetime.datetime.fromisoformat(obj["last_checked_at"])
    return obj


def rebuild_post_fields(post):
    if post is None:
        return
    if post.get("added"):
        post["added"] = datetime.datetime.fromisoformat(post["added"])
    if post.get("published"):
        post["published"] = datetime.datetime.fromisoformat(post["published"])
    if post.get("edited"):
        post["edited"] = datetime.datetime.fromisoformat(post["edited"])
    return post


def prepare_post_fields(post):
    if post.get("added"):
        post["added"] = post["added"].isoformat()
    if post.get("published"):
        post["published"] = post["published"].isoformat()
    if post.get("edited"):
        post["edited"] = post["edited"].isoformat()
    return post


# def date_safe_serialize_post_list(data, encoder):
#     return encoder([prepare_post_fields(x) for x in copy.deepcopy(data)])

# def date_safe_serialize_post(data, encoder):
#     return encoder(prepare_post_fields(copy.deepcopy(data)))
