import json
import requests
import time
from datetime import datetime
from secrets import spotify_user_id
from secrets import queue_id
from secrets import rotation_id
from refresh import Refresh

precheck = 0
temp = "xxx"
queue_max =  5 # NOTE: <== Your preffered QUEUE size.
queue_count = 0
queue_dif = 0
notune = 0

print(" ")
print("[•_•] BOTIFY maintains a QUEUE playlist, fed by the")
print("Least Recently Played tracks from a CYCLIC playlist.")
print("Lockdown Edition: 26-Jan-2021 @ 18:21 (c) Viking Designs.")
print("Current User: " + spotify_user_id)
print(" ")

class RunBotify:
    def __init__(self):
        self.user_id = spotify_user_id
        self.spotify_token = ""
        self.nowtrack = ""
        self.newtracks = ""
        self.que_playlist_id = queue_id
        self.rot_playlist_id = rotation_id
        self.get_artist = ""
        self.get_album = ""
        self.get_year = ""

    def get_now_playing_track(self):
        global precheck, notune
        if precheck == 0:
            precheck = 1
            self.get_track_total_from_queue()

        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 notune == 0:
                print("No Track Playing!")
            time.sleep(10)
            notune = notune + 1

            if notune != 90:
                self.get_now_playing_track()
            notune = 0
            print("[0] Refresh Access Token.")
            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"]
        self.get_album =  json_data["item"]["album"]["name"]
        self.get_year = json_data["item"]["album"]["release_date"][:4]

        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("Title       " + json_data["item"]["name"] + ".")
            print("Artist      " + self.get_artist + ".")
            print("Album       " + self.get_album + ".")
            print("Release     " + self.get_year + ".")
             
            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_queue()
            self.remove_track_from_rotation()
            self.add_track_to_rotation()
            self.get_track_total_from_queue()

        while True:
            time.sleep(3)
            self.get_now_playing_track()

    def remove_track_from_queue(self):
        print("[2] Remove  track from QUEUE.")
        query = "https://api.spotify.com/v1/playlists/{}/tracks".format(self.que_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 remove_track_from_rotation(self):
        print("[3] Remove  track from start of RECYCLE.")
        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("[4] Replace track to the end of 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 get_track_total_from_queue(self):
        query = "https://api.spotify.com/v1/playlists/{}/tracks".format(self.que_playlist_id)
        headers={"Content-type": "application/json","Authorization":"Bearer {}".format(self.spotify_token)}
        response = requests.request("get", url=query, headers=headers)
        response_json = response.json()
        
        queue_tot = 0
        for i in response_json["items"]:
            queue_tot =  queue_tot + 1

        print("[=] Current total '" + str(queue_tot) + "' tracks in the QUEUE.")
        if queue_tot < queue_max:
            self.get_rotation_tracks(queue_tot)

    def get_rotation_tracks(self, queue_tot):
        global queue_count, queue_dif
        # NOTE: QUEUE DIFF is the difference between the QUEUE MAX and current QUEUE TOTAL.
        queue_count = queue_max
        queue_dif = queue_count - queue_tot

        print("[<] Getting '" + str(queue_dif) + "' fresh track from RECYCLE.")
        query = "https://api.spotify.com/v1/playlists/{}/tracks".format(self.rot_playlist_id)
        params={"limit":queue_count}
        headers={"Content-type": "application/json","Authorization":"Bearer {}".format(self.spotify_token)}
        response = requests.request("get", url=query, headers=headers, params=params)
        response_json = response.json()

        self.newtracks = ""
        for i in response_json["items"]:
            self.newtracks += i["track"]["uri"] + ","
        
        # NOTE: The variable 'add_pos' is the position in the 'newtracks' data where the
        # NOTE: 'addition' point should start, thus skipping those tracks already in QUEUE.
        add_pos = (queue_dif * 37) # NOTE: 37 bits of data per track URI.
        self.newtracks = self.newtracks[-(add_pos):-1]

        # NOTE: New part to Get 'Date and Time' track was added to FEED playlist.
        if queue_dif == 1:
            x = response_json["items"][0]["added_at"]
            d  = x[8:10]
            m  = x[5:7]
            y  = x[0:4]
            h  = x[11:13]
            mn = x[14:16]
            s  = x[17:19]

            last_played = d + "/" + m + "/" + y + " @ " + h + ":" + mn + ":" + s
            print("[•] Was added to RECYCLE on " + last_played + ".")
            last_played_date = d + "/" + m + "/" + y     # print("[TEST] Last played date:  " + last_played_date)

            now = datetime.now()    
            todays_date = now.strftime("%d/%m/%Y")       # print("[TEST] Todays date:       " + todays_date)

            d1 = last_played_date
            d2 = todays_date
            d1 = datetime.strptime(d1, "%d/%m/%Y")
            d2 = datetime.strptime(d2, "%d/%m/%Y")
            dx = abs((d2 - d1).days)
            print("[•] Added or Last played " + str(dx) + " days ago.")
        # NOTE: New part - *** END ***

        self.add_to_queue()

    def add_to_queue(self):
        global queue_dif
        print("[+] Adding  '" + str(queue_dif) + "' fresh track to the QUEUE.")
        query = "https://api.spotify.com/v1/playlists/{}/tracks?uris={}".format(self.que_playlist_id, self.newtracks)
        headers={"Content-type": "application/json","Authorization": "Bearer {}".format(self.spotify_token)}
        # NOTE: Keep 'POST' (append) as 'PUT' (replace) removes any remaining tracks from QUEUE.
        response = requests.request("post", url=query, headers=headers)

    def call_refresh(self):
        refreshCaller = Refresh()
        self.spotify_token = refreshCaller.refresh()
        self.get_now_playing_track()

a = RunBotify()
a.call_refresh()
 