import spotipy
from spotipy.oauth2 import SpotifyOAuth
from time import sleep
import threading

class Spotify:
    def __init__(self):
        self.sp = self.authenticate()
        self.set_values()
        pass

    def authenticate(self):
        scope = ["user-read-playback-state", "user-modify-playback-state", "user-read-currently-playing", "user-read-playback-position", "user-library-modify"]
        sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope))
        return sp

    def set_values(self):
        song = self.sp.current_playback()
        self.currently_playing = song
        if song:
            self.current_context = song["context"]["type"]
            self.current_context_uri = song["context"]["uri"]
            self.set_context()
            self.song_artists = []
            for artist in song["item"]["artists"]:
                self.song_artists.append(artist["name"])
            self.song_name = song["item"]["name"]
            self.song_length = song["item"]["duration_ms"]
            self.song_played = song["progress_ms"]

    def set_context(self):
        if self.current_context == "artist":
            artist = self.sp.artist(self.current_context_uri)
            if artist:
                self.current_context_name = artist["name"]
        if self.current_context == "playlist":
            playlist = self.sp.playlist(self.current_context_uri)
            if playlist:
                self.current_context_name = playlist["name"]
        if self.current_context == "album":
            album = self.sp.album(self.current_context_uri)
            if album:
                self.current_context_name = album["name"]

    def start_update_loop(self):
        thread = threading.Thread(target=self.update_loop)
        thread.daemon = True
        thread.start()

    def update_loop(self):
        while True:
            sleep(5)
            self.set_values()
