import os
import json
import requests
import time
from secrets import spotify_user_id, playlist1950_id, playlist1960_id, playlist1970_id, playlist1980_id, playlist1990_id, playlist2000_id, playlist2010_id, playlist2020_id, playlistodds_id
from refresh import Refresh

refreshCaller = Refresh()
job_done = False
#+++++++++++++++++++++++++++++++++++++++++++++++++++++
#Enter playlist ID to be added to Decades here
playlist_to_add = '3w0VOjgeSWRyOKjI21yrPT'
#+++++++++++++++++++++++++++++++++++++++++++++++++++++
os.system('cls')
print("[•_•] Decades - Put any Playlist Tracks into Decadic Playlists")
print("Depending on the Release date of the track concerned")
print("Version 2.3.0 : 16-MAR-2021 @ 16:20 (c) Viking Design. (^o.o^)")
print("Enter the desired Playlist id in the playlist_to_add variable in line 12 above")
print("In the format playlist_to_add = '5CHUxOspd44zpbkLTi2RLD'")
print("User: " + spotify_user_id)

class Decades:
    def __init__(self):
        self.user_id = spotify_user_id
        self.playlist_id = playlist_to_add
        self.play5 = playlist1950_id
        self.play6 = playlist1960_id
        self.play7 = playlist1970_id
        self.play8 = playlist1980_id
        self.play9 = playlist1990_id
        self.play0 = playlist2000_id
        self.play1 = playlist2010_id
        self.play2 = playlist2020_id
        self.play3 = playlistodds_id
        self.play4 = playlistodds_id
        self.spotify_token = ""
        self.more_than_fifty = 0
        self.here_i_am = os.path.dirname(os.path.abspath(__file__))
        
    def do_the_business(self):
        tic = time.perf_counter()
        while True:
            self.call_refresh()
            self.check_playlist_not_done()
            self.get_track_count_from_playlist()
            self.get_track_from_playlist()
            if job_done:
                toc = time.perf_counter()
                ty_res = time.gmtime(toc - tic)
                res = time.strftime("%H Hours :%M Minutes :%S Seconds",ty_res)
                print(f"Decades Took {res} To Add {self.total} Records To The Decadic Playlists" )
                return

    def check_playlist_not_done(self):
        try:
            if os.path.exists(self.here_i_am + r"\Playlists Completed - " + spotify_user_id + ".txt") is False:
                return        
            File_object = open(self.here_i_am + r"\Playlists Completed - " + spotify_user_id + ".txt","r")
            count = 0
            for line in File_object.readlines():
                count += 1
                if line.strip() == playlist_to_add:
                    os.system('cls')
                    print("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
                    print("Playlist with ID " + playlist_to_add + " Has Been Added Already!")
                    print()
                    print("Please check this is what you want and delete the ID from the...")
                    print()
                    print(self.here_i_am + r"\Playlists Completed - " + spotify_user_id + ".txt File")
                    print()
                    print("Failure To Check This Will Result In MANY DUPLICATES !!!!!!!!!!!!!!!!!!!!!!!!")
                    print("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
                    exit()
        except:
            exit()

    def get_track_count_from_playlist(self):
        params={"limit":50,"offset":self.more_than_fifty}
        query = "https://api.spotify.com/v1/users/{}/playlists".format(self.user_id)
        response = requests.request("get", url=query, headers={"Content-type": "application/json","Authorization":"Bearer {}".format(self.spotify_token)},params=params)
        response_json = response.json()
        for i in response_json["items"]:
            if (i["id"]) == self.playlist_id:
                self.playlist_name = (i["name"])
                self.total = (i["tracks"]["total"])
        if self.more_than_fifty == 0:
            self.more_than_fifty = 50
            self.get_track_count_from_playlist()
        return

    def get_track_from_playlist(self):
        global  job_done
        for i in range (self.total):
            self.offset = i
            query = "https://api.spotify.com/v1/playlists/{}/tracks".format(self.playlist_id)
            response = requests.request("get", url=query, headers={"Content-type": "application/json","Authorization":"Bearer {}".format(self.spotify_token)}, params={"limit":100,"offset":self.offset})
            response_json = response.json()
            json_data = json.loads(response.text)
            self.track_uri = json_data["items"][0]["track"]["uri"]
            self.decade = int(json_data["items"][0]["track"]["album"]["release_date"][2:3])
            if response.status_code == 200:
                playlist_list = [self.play0, self.play1, self.play2, self.play3, self.play4, self.play5, self.play6, self.play7, self.play8, self.play9]
                self.new_playlist_id = playlist_list[self.decade]
                self.add_to_playlist()
            else:
                print("Failed with response code " + response.status_code)
                exit()
        File_object = open(self.here_i_am + r"\Playlists Completed - " + spotify_user_id + ".txt","a")
        File_object.writelines([str(self.playlist_id) + "\n"])
        File_object.close()
        job_done = True

    def add_to_playlist(self):
        query = "https://api.spotify.com/v1/playlists/{}/tracks?uris={}".format(self.new_playlist_id, self.track_uri)
        response = requests.post(query, headers={"Content-Type": "application/json","Authorization": "Bearer {}".format(self.spotify_token)})
 
    def call_refresh(self): #NOTE Euans 2nd Fix
        global refreshCaller
        while True:
            self.spotify_token = refreshCaller.refresh()
            if self.spotify_token == -1:
                print("==============================\n[!] Error refreshing token, retrying in 30 Seconds\n==============================")
                time.sleep(30)
            else:
                break
        
a = Decades()
a.call_refresh()
a.do_the_business()