from email.message import EmailMessage
import smtplib
import base64
import sys, os
#CHANGE THIS TO WHERE YOUR secrets.py and database FILES ARE
sys.path.insert(1, 'j:\\Spotty\secrets_and_database')
from refresh import Refresh
import json, requests, time
from does_everything_secrets import spotify_user_id

refreshCaller = Refresh()

class unplay:
    def __init__(self):
        self.email_address = "vikingindustries2023@gmail.com"
        self.email_password = b'dGFvZSBlZnluIHF2dmwgZnZ4eQ=='
        self.bitpassword = base64.b64decode(self.email_password)
        self.email_password = self.bitpassword.decode('utf-8')
        self.spotify_token = ""
        self.market = "GB"
        self.unplay_uri = []
        self.unplay_track = []
        self.unplay_artist = []
        self.message = ""
        #######################################################################################
        ############################### Enter Playlist to check here ##########################
        self.playlist_to_check = "32WUNBMwwodIsdtdhWkHGD"
        #######################################################################################

    def avail_test(self):
        os.system('cls')
        print("\033[91mUnavailable v.2.1.0 == Enter Playlist to check ID in Line 27 and adjust line 6 to your path ...\033[0m")
        print("\033[91mRemoves Tracks UNPLAYABLE from chosen playlist and emails user with results.\033[0m")
        print("\033[33m..Only suitable for use with 'personal' playlists as it can't remove tracks from other peoples playlists\033[0m")
        print("\033[33m... Suitable for use with MASTER or ENDLESS FEED Playlist and others in your library ...\033[0m")
        self.get_source_info()
        self.check_source_tracks()
        self.remove_unplayable()
        self.add_to_message()
        self.send_message()
        print()
        print()

    def get_source_info(self):
        query = "https://api.spotify.com/v1/playlists/{}".format(self.playlist_to_check)
        response = requests.request("get", url=query, headers={"Content-type": "application/json", "Authorization": "Bearer {}".format(self.spotify_token)})
        json_data = json.loads(response.text)
        self.queue_total = (json_data["tracks"]["total"])
        self.playlist_name = (json_data["name"])

    def check_source_tracks(self):
            t = 0
            while t < self.queue_total:
                print("Checking Track " + str(t) + " of " + str(self.queue_total), end='\r')
                try:
                    if t > 99:
                        if str(t)[-3:] == "000":
                            self.call_refresh()
                    self.offset = t
                    query = "https://api.spotify.com/v1/playlists/{}/tracks".format(self.playlist_to_check)
                    response = requests.request("get", url=query, headers={"Content-type": "application/json", "Authorization": "Bearer {}".format(self.spotify_token)}, params={"limit": 1, "market": self.market, "offset": self.offset})
                    json_data = json.loads(response.text)
                    self.track_uri = json_data["items"][0]["track"]["uri"]
                    self.track_name = json_data["items"][0]["track"]["name"]
                    self.artist_name = json_data["items"][0]["track"]["artists"][0]["name"]
                    self.not_playable = json_data["items"][0]["track"]["is_playable"]
                    if response.status_code == 200:
                        if not self.not_playable:
                            self.unplay_uri.append(self.track_uri)
                            self.unplay_track.append(self.track_name)
                            self.unplay_artist.append(self.artist_name)
                            t += 1
                        else:
                            t = t + 1
                            continue
                except:
                    print()
                    print("Get Source Track error  " + str(t))
                    continue

    def remove_unplayable(self):
        print()
        print("Removing Unplayable Tracks")
        print()
        unp = 0
        while unp < len(self.unplay_uri):
            query = "https://api.spotify.com/v1/playlists/{}/tracks".format(self.playlist_to_check)
            response = requests.request("delete", url=query, headers={"Content-type": "application/json", "Authorization": "Bearer {}".format(self.spotify_token)}, data=json.dumps({"tracks": [{"uri": self.unplay_uri[unp]}]}))
            unp+=1
        return

    def add_to_message(self):
        t = 0
        while t < len(self.unplay_uri):
            self.message = self.message + str(self.unplay_uri[t]) + " - " + str(
                self.unplay_track[t]) + " - " + str(self.unplay_artist[t]) + "\n\n"
            t += 1
            continue

    def send_message(self):
        print("Sending Message")
        if self.message == "":
            self.message = "No Unplayable Tracks Found....."
        if spotify_user_id == "daftjoe":
            addressee = "allanlockwoodsmith@gmail.com"
        if spotify_user_id == "hddd-1960":
            addressee = "peter.eddowes@gmail.com"
        msg = EmailMessage()
        msg['Subject'] = self.playlist_name + ". Unplayable Tracks Removed."
        msg['From'] = self.email_address
        msg['To'] = addressee
        msg.set_content("The following tracks were found unplayable in playlist - " + self.playlist_name + "\n and have been removed! \n Review them and replace with working versions if applicable \n\n" + self.message + "\n\n DO NOT REPLY TO THIS EMAIL IT IS NOT MONITORED!")

        with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
            smtp.login(self.email_address, self.email_password)
            smtp.send_message(msg)

    def call_refresh(self):
        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 = unplay()
a.call_refresh()
a.avail_test()