import datetime

from src.internals.serializers import unsafe_dumper, unsafe_loader


def serialize_artists(artists, dumper=unsafe_dumper):
    return dumper(artists)


def deserialize_artists(artists_str, loader=unsafe_loader):
    artists = loader(artists_str)
    for element in artists:
        rebuild_artist_fields(element)
    return artists


def serialize_artist(artist, dumper=unsafe_dumper):
    return dumper(artist)


def deserialize_artist(artist_str, loader=unsafe_loader):
    artist = loader(artist_str)
    if artist is not None:
        rebuild_artist_fields(artist)
    return artist


def prepare_artist_fields(artist):
    artist["indexed"] = artist["indexed"].isoformat()
    artist["updated"] = artist["updated"].isoformat()
    return artist


def rebuild_artist_fields(artist):
    artist["indexed"] = datetime.datetime.fromisoformat(artist["indexed"])
    artist["updated"] = datetime.datetime.fromisoformat(artist["updated"])
    return artist
