from .models import Track, Vote, Album, Artist
from random import choice, seed

def from_json(cls, json):
    try:
        return cls.objects.get(pk=json["id"])
    except cls.DoesNotExist:
        keys = [f.name for f in cls._meta.get_fields()]
        subset = {key:json[key] for key in set(keys) & set(json.keys())}
        return cls.objects.create(**subset)

def get_unvoted(user):
    """Gets next voting track for user. Returns a pair with track and flag if this was a skipped track"""
    votes = set(Vote.objects.filter(user=user).values_list('track_id', flat=True))
    tracks = set(Track.objects.filter(banter_done=True).values_list('pk', flat=True))
    seed(user.username)
    try:
        queue = list(tracks - votes)
        skipped = False
        if not queue:
            skipped = True
            queue = list(Vote.objects.filter(user=user).filter(skipped=True).values_list('track_id', flat=True))
        random_track = choice(queue)
        choice 
        return (Track.objects.get(pk=random_track), skipped)
    except IndexError:
        return (None, False)
    
def get_unvoted_count(user):
    votes = set(Vote.objects.filter(user=user).values_list('track_id', flat=True))
    tracks = set(Track.objects.filter(banter_done=True).values_list('pk', flat=True))
    try:
        queue = list(tracks - votes)
        skipped = list(Vote.objects.filter(user=user).filter(skipped=True).values_list('track_id', flat=True))
        return (len(queue), len(skipped))
    except IndexError:
        return (0, 0)
    

def track_from_json(json):
    """Creates the track, album and artist from spotify response."""
    # Album artists
    album_artists = []
    for artist in json["album"]["artists"]:
        album_artists.append(from_json(Artist, artist))
    del json["album"]["artists"]

    # Album
    album = from_json(Album, json["album"])
    album.image_url = json["album"]["images"][0]["url"]
    album.save()
    del json["album"]
    for artist in album_artists:
        album.artists.add(artist)

    # Track artists
    track_artists = []
    for artist in json["artists"]:
        track_artists.append(from_json(Artist, artist))
    del json["artists"]

    # Track
    track = from_json(Track, json)
    for artist in track_artists:
        track.artists.add(artist)
    track.album = album
    track.save()
    return track
