from email.message import EmailMessage
import smtplib
import base64
import sys, os

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.track_lenth = ""
        self.long_uri = []
        self.long_track = []
        self.long_artist = []
        self.message = ""

        ## Enter Playlist to check here ##################
        ## PLAYLIST = "xxxxxxxxxxxx" ##
        self.playlist_to_check = "2FDEDaf02jCJv9J7Y3bu7b"
        ##################################################

    def avail_test(self):
        os.system('cls')
        print("REMOVE LONG TRACKS ~ 06-03-2023 (CURRENT SETTING =  6 MINS 00 sec [360] seconds)")
        self.get_source_info()
        self.check_source_tracks()
        self.remove_unplayable()
        self.add_to_message()
        self.send_message()
        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"]
                    self.track_lenth = json_data["items"][0]["track"]["duration_ms"]

                    ## Check if lenth of track is greater than 6 mins (360 seconds), if yes then remove.
                    track_lenth = int(self.track_lenth /1000)
                    if track_lenth > 330:
                        print('Track: ' + self.track_name + ' [lenth: ' + str(track_lenth)  + ']')
                        self.long_uri.append(self.track_uri)
                        self.long_track.append(self.track_name)
                        self.long_artist.append(self.artist_name)
                        t += 1
                    else:
                        t = t + 1
                except:
                    continue


    def remove_unplayable(self):
        print()
        print("REMOVING LONG TRACKS")
        print()
        unp = 0
        while unp < len(self.long_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.long_uri[unp]}]}))
            unp+=1
        return

    def add_to_message(self):
        t = 0
        while t < len(self.long_uri):
            self.message = self.message + str(self.long_uri[t]) + " - " + str(
                self.long_track[t]) + " - " + str(self.long_artist[t]) + "\n\n"
            t += 1
            continue

    def send_message(self):
        print("Sending Message")
        if self.message == "":
            self.message = "No LONG 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 + ". Tracks over 6 mins removed."
        msg['From'] = self.email_address
        msg['To'] = addressee
        msg.set_content("The following tracks were found be TOO LONG in playlist - " + self.playlist_name + "\n and have been removed! \n Review them and replace with RADIO EDIT versions if applicable \n\n" + self.message + "\n\n PLEASE DO NOT REPLY TO THIS EMAIL AS 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()
