import json
import requests
import time
from datetime import datetime
from secrets import spotify_user_id
from secrets import feed_id
from refresh import Refresh

temp = "xxx"
count = 0

print("[•_•] -BOTIFY")
print("Super Slim Edition: 29-JAN-21 @ 18:50 (c) Viking Design.")
print("User: " + spotify_user_id)

class RunBotify:
    def __init__(self):
        self.user_id = spotify_user_id
        self.spotify_token = ""
        self.nowtrack = ""
        self.rot_playlist_id = feed_id
        self.get_artist = ""

    def get_now_playing_track(self):
        global count
        query = "https://api.spotify.com/v1/me/player/currently-playing"
        headers={"Content-type": "application/json","Authorization": "Bearer {}".format(self.spotify_token)}
        response = requests.request("get", url=query, headers=headers)

        if response.status_code == 204:
            if count == 0:
                print("No Track Playing!")
            time.sleep(10)
            count = count + 1
            print("35 Count...")
            print(count)
        
            if count != 90:
                self.get_now_playing_track()
            #count = 0
            print("[0] Refresh Access Token")
            print("41 Count...")
            print(count)
            self.call_refresh()

            query = "https://api.spotify.com/v1/me/player/currently-playing"
            headers={"Content-type": "application/json","Authorization": "Bearer {}".format(self.spotify_token)}
            response = requests.request("get", url=query, headers=headers)

        json_data = json.loads(response.text)
        self.nowtrack = json_data["item"]["uri"]
        self.get_artist = json_data["item"]["album"]["artists"][0]["name"]

        #print(json_data["items"][0]["track"]["popularity"])
        #print(json_data(i["uri"]))
        #print(json_data["items"][0]["album"]["artists"][0]["name"])
        #print(json_data["items"][0]["album"]["name"])
    
        print("=================================================")

        #print(json_data["item"])
        #print(json_data["context"]["external_urls"])
        #print(json_data["context"]["external_urls"]["spotify"])
        #print(json_data["context"]["href"])
        #print(json_data["context"]["type"])
        #print(json_data["context"]["uri"])
        #print(json_data["progress_ms"])
        #print(json_data["is_playing"])
        #print(json_data["item"]["album"]["album_type"])
        #print(json_data["item"]["album"]["artists"][0]["external_urls"])
        #print(json_data["item"]["album"]["artists"][0]["external_urls"]["spotify"])
        #print(json_data["item"]["album"]["artists"][0]["href"])
        #print(json_data["item"]["album"]["artists"][0]["id"])
        #print(json_data["item"]["album"]["artists"][0]["name"])
        #print(json_data["item"]["album"]["artists"][0]["type"])
        #print(json_data["item"]["album"]["artists"][0]["uri"])
        #print(json_data["item"]["album"]["available_markets"])
        #print(json_data["item"]["album"]["external_urls"])
        #print(json_data["item"]["album"]["external_urls"]["spotify"])
        #print(json_data["item"]["album"]["href"])
        #print(json_data["item"]["album"]["id"])
        #print(json_data["item"]["album"]["images"][0]["url"])
        #print(json_data["item"]["album"]["images"][1]["url"])
        #print(json_data["item"]["album"]["images"][2]["url"])
        #print(json_data["item"]["album"]["name"])
        #print(json_data["item"]["album"]["release_date"])
        #print(json_data["item"]["album"]["release_date_precision"])
        #print(json_data["item"]["album"]["total_tracks"])
        #print(json_data["item"]["album"]["type"])
        #print(json_data["item"]["album"]["uri"])
        #print(json_data["item"]["artists"][0]["external_urls"])
        #print(json_data["item"]["artists"][0]["external_urls"]["spotify"])
        #print(json_data["item"]["artists"][0]["href"])
        #print(json_data["item"]["artists"][0]["id"])
        #print(json_data["item"]["artists"][0]["name"])
        #print(json_data["item"]["artists"][0]["type"])
        #print(json_data["item"]["artists"][0]["uri"])
        print(json_data["item"]["available_markets"])
        print(json_data["item"]["disc_number"])
        print(json_data["item"]["duration_ms"])
        print(json_data["item"]["explicit"])
        print(json_data["item"]["external_ids"])
        print(json_data["item"]["external_ids"]["isrc"])
        print(json_data["item"]["external_urls"])
        print(json_data["item"]["external_urls"]["spotify"])
        print(json_data["item"]["href"])
        print(json_data["item"]["id"])
        print(json_data["item"]["is_local"])
        print(json_data["item"]["name"])
        print(json_data["item"]["popularity"])
        print(json_data["item"]["preview_url"])
        print(json_data["item"]["track_number"])
        print(json_data["item"]["type"])
        print(json_data["item"]["uri"])
        exit()
   
        global temp                               
        if temp != self.nowtrack:
            prevtrack = temp
            temp = self.nowtrack 
            now = datetime.now()    
            date_time = now.strftime("%d/%m/%Y at %H:%M:%S")
            print("--------------------------------------------------------") 
            print(date_time)
            print(" • " + json_data["item"]["name"])
            print(" • " + self.get_artist)
             
            self.call_refresh()
            print("[1] Refresh Access Token")
            self.nowtrack = prevtrack
            self.played_track_manager()

    def played_track_manager(self):
        if self.nowtrack != "xxx":
            self.remove_track_from_rotation()
            self.add_track_to_rotation()

        while True:
            time.sleep(3)
            self.get_now_playing_track()

    def remove_track_from_rotation(self):
        query = "https://api.spotify.com/v1/playlists/{}/tracks".format(self.rot_playlist_id)
        headers={"Content-type": "application/json","Authorization":"Bearer {}".format(self.spotify_token)}     
        params = {"tracks": [{"uri": self.nowtrack}]}
        response = requests.request("delete", url=query, headers=headers, data=json.dumps(params))

    def add_track_to_rotation(self):
        print("[2] Update LAST PLAYED track in RECYCLE.")

        query = "https://api.spotify.com/v1/playlists/{}/tracks?uris={}".format(self.rot_playlist_id, self.nowtrack)
        headers={"Content-type": "application/json","Authorization":"Bearer {}".format(self.spotify_token)}
        response = requests.request("post", url=query, headers=headers)

    def call_refresh(self):
        global count
        refreshCaller = Refresh()
        self.spotify_token = refreshCaller.refresh()
        count = 0
        self.get_now_playing_track()

a = RunBotify()
a.call_refresh()
