import json
import operator
from collections import Counter
import dateutil
from matplotlib import pyplot as plt, rcParams
import datetime

rcParams['figure.autolayout'] = True

with open('scrobbles.db', 'rb') as f:
    data = json.load(f)

scrobbles = data['scrobbles']
for scrobble in scrobbles:
    # parse into a datetime.datetime
    scrobble['datetime'] = dateutil.parser.parse(scrobble['datetime'])

scrobbles.sort(key=lambda scr: scr['datetime'])


def same_week(d1, d2):
    return d1.isocalendar()[1] == d2.isocalendar()[1] \
              and d1.year == d2.year

grouped_scrobbles = [[scrobbles[0]]]
for scrobble in scrobbles:
    if same_week(scrobble['datetime'], grouped_scrobbles[-1][0]['datetime']):
        grouped_scrobbles[-1].append(scrobble)
    else:
        grouped_scrobbles.append([scrobble])

def bestArtists(week, n = 3):
    c = Counter([s['artist'] for s in week])
    return [a[0] for a in c.most_common(n)]

bestArtistsPerWeek = [*map(bestArtists, grouped_scrobbles)]

import code
code.interact(local=locals())

def concat(lsts):
    if not lsts:
        return []
    lst = lsts.pop()
    return concat(lsts) + lst

bestArtists = concat(bestArtistsPerWeek)
artists = set(bestArtists)

data = []

for artist in artists:
    data.append((artist, bestArtists.count(artist)))

data.sort(key=operator.itemgetter(1))

plt.bar(range(len(data)), [a[1] for a in data])
plt.xticks(range(len(data)), [a[0] for a in data], rotation=90)
plt.show()
