
# from __future__ import unicode_literals, absolute_import
import requests
from requests_oauthlib import OAuth1Session
import sys
import os
import os.path
import keyring
import difflib

git_sub_modules = './' #Relative paths ok too
for dir in os.listdir(git_sub_modules):
    path = os.path.join(git_sub_modules, dir)
    if not path in sys.path:
        sys.path.append(path)

from pyItunes import *

rdioURL = "http://api.rdio.com/1/"
request_token_url = "http://api.rdio.com/oauth/request_token"
base_authorization_url = "https://www.rdio.com/oauth/authorize"
access_token_url = "http://api.rdio.com/oauth/access_token"

client_key = "jbu8brgbmq63qazzvttsnv5g"
client_secret = "U2HTvUraQ8"

class CommonEqualityMixin(object):
    def __hash__(self):
        if self.__dict__ is not None:
            return self.__dict__.__hash__()
        else:
            return 0

    def __eq__(self, other):
        if type(other) is type(self):
            return self.__dict__ == other.__dict__
        else:
            return False

    def __ne__(self, other):
        return not self.__eq__(other)

    def __repr__(self):
        return self.__unicode__()

class Song(CommonEqualityMixin):
    def __init__(self, title, album="", artist="", playCount=0):
        self.title = title
        self.album = album
        self.artist = artist
        self.playCount = playCount

    def __unicode__(self):
        return "{0.title},{0.artist},{0.album}".format(self)


class Album(CommonEqualityMixin):
    def __init__(self, title, artist="", tracks=None):
        self.title = title
        self.artist = artist
        self.tracks = tracks
        self.playCount = 0
        if self.tracks is not None:
            self.playCount = sum([track.playCount for track in self.tracks])/len(self.tracks)

    def plays(self):
        if self.tracks is not None and self.playCount == 0:
            self.playCount = sum([track.playCount for track in self.tracks])/len(self.tracks)
        return self.playCount


    def __eq__(self, other):
        if type(other) is type(self):
            if self.title is None or other.title is None or self.artist is None or other.artist is None:
                # print self
                # print other
                return self.title == other.title and self.artist == other.artist
            else:
                titleRatio = difflib.SequenceMatcher(None, self.title.lower(), other.title.lower()).ratio()
                artistRatio = difflib.SequenceMatcher(None, self.artist.lower(), other.artist.lower()).ratio()
                # print "{0} {1}".format(titleRatio, artistRatio)
                close = titleRatio > 0.75 and artistRatio > 0.75
                # if close and (titleRatio < 1 or artistRatio < 1):
                #     print("{0}/{1}:{2}\n\t{3}/{4}:{5}".format(self.title, other.title, titleRatio, self.artist, other.artist, artistRatio))
                return close
        else:
            return False

    def __hash__(self):
        if self.__dict__ is not None:
            dic = self.__dict__
            tup = tuple(dic)
            has = hash(tup)
            return has
        else:
            return 0

    def __unicode__(self):
        self.plays()
        return "{0.title}: \t {0.artist} ({0.playCount})".format(self)

class Artist(CommonEqualityMixin):
    def __init__(self, name, albums=None):
        self.name = name
        self.albums = albums

    def __unicode__(self):
        return self.name

def songListToAlbumList(songs):
    albums = {}
    for song in songs:
        if song.album is not None and song.artist is not None:
            if song.album.lower() in albums:
                albums[song.album.lower()].tracks.append(song)
            else:
                newAlbum = Album(song.album, song.artist, [song])
                albums[song.album.lower()] = newAlbum
    return list(albums.values())


def authenticate():
    oauth = OAuth1Session(client_key, client_secret=client_secret, callback_uri="oob")

    fetch_response = oauth.fetch_request_token(request_token_url)
    resource_owner_key = fetch_response.get('oauth_token')
    resource_owner_secret = fetch_response.get('oauth_token_secret')
    authorization_url = oauth.authorization_url(base_authorization_url)
    print('Please go here and authorize,', authorization_url)
    verifier = input('Paste the PIN here: ')

    rdio = OAuth1Session(client_key,
                client_secret=client_secret,
                resource_owner_key=resource_owner_key,
                resource_owner_secret=resource_owner_secret,
                verifier=verifier)

    oauth_tokens = rdio.fetch_access_token(access_token_url)
    keyring.set_password("rdioExporty", "token", oauth_tokens['oauth_token'])
    keyring.set_password("rdioExporty", "secret", oauth_tokens['oauth_token_secret'])
    return rdio

def reAuthenticate():
    rdio = None
    token = keyring.get_password("rdioExporty", "token")
    secret = keyring.get_password("rdioExporty", "secret")
    if token is not None and secret is not None:
        rdio = OAuth1Session(client_key,
                      client_secret=client_secret)
        rdio._populate_attributes({'oauth_token': token,
                      'oauth_token_secret': secret})
    else:
        rdio = authenticate()
    return rdio


rdio = reAuthenticate()

# Get user ID
userIDAns = rdio.post(rdioURL, {'method': "currentUser"})
userJson = None
try:
    userJson = userIDAns.json()
except ValueError:
    print(userIDAns)
    print(userIDAns.text)
if userJson['status'] != 'ok':
    print(userIDAns)
    sys.exit(0)
userID = userJson['result']['key']

# Get rdio songs

songs = rdio.post(rdioURL, {'method': 'getTracksInCollection', 'user': userID, 'sort': 'playCount', 'extras': 'playCount'}).json()['result']

print("You have {0} tracks in your rdio library.".format(len(songs)))

songlist = []
for song in songs:
    newSong = Song(song['name'],song['artist'],song['album'])
    if 'playCount' in song:
        newSong.playCount = song['playCount']
    songlist.append(newSong)


albumlist = set(songListToAlbumList(songlist))

# Read iTunes Library

homeDir = os.getenv("HOME")
iTunesDir = os.path.join(homeDir, "Music", "iTunes", "iTunes Music Library.xml")
iLibrary = Library(iTunesDir)

iSonglist = [Song(song[1].name, song[1].artist, song[1].album) for song in list(iLibrary.songs.items())]

iAlbumlist = set(songListToAlbumList(iSonglist))

print("You have {0} tracks in your iTunes library.".format(len(iSonglist)))

rdioOnly = [x for x in songlist if x not in iSonglist]
itunesOnly = [x for x in iSonglist if x not in songlist]

print("Only in rdio, {0} tracks.".format(len(rdioOnly)))
print("Only in iTunes {0} tracks.".format(len(itunesOnly)))
print("In both, {0} tracks.".format(len(songlist) - len(rdioOnly)))

listyiAlbums = list(iAlbumlist)
overlap = [album for album in albumlist if album in listyiAlbums]

print("rdio albums: {0}, iTunes albums {1}, overlap {2}".format(len(albumlist), len(iAlbumlist), len(overlap)))

toBuy = [album for album in albumlist if album not in listyiAlbums]

toBuy.sort(key = lambda x: x.plays())

print("\n\n")

for album in toBuy:
    print(album)




