#################################
## NOTE: READ THE NOTES PLEASE ##
#################################

## NOTE: READING - ALL YOU (SHOULD) NEED TO KNOW ##
## https://www.geeksforgeeks.org/mouse-keyboard-automation-using-python/

## NOTE:  ALL THE PYAUTOGUI BITS ##
## https://pyautogui.readthedocs.io/en/latest/index.html

## NOTE:  DO THIS BIT FIRST ##
## Note: pip3 install pyautogui

## NOTE: YOU "MAY" NEED THIS - IF ONLY TP PLACE CURSOR "OUT OF THE WAY" ##
## size():
## Function used to get Screen resolution of Windows PC.
## Size(width=1600, height=900) ## NOTE: <=== My VERY old laptop with strange screen res ## 
## print(pyautogui.size())

## NOTE: YOU WILL NEED THIS TO CAPTURE MOUSE POINTER  - ADD a 10 sec DELAY TO GIVE YOU,
## NOTE: TIME TO SET THE FOCUS ON THE CHROME BROWSER WEB PAGES RUNNING RVRB ##
## position():
## Function to get current position of the mouse pointer. 
## print(pyautogui.position())

## NOTE: YOU WILL NEED TO ADD THE X and Y CO-ORDINANTS FOR "YOUR" SCREEN ##
## click():
## Function used for clicking (and the mouse.

## NOTE: EXAMPLE OF A MOUSE CLICK TO "SKIP TRACK" ON RVRB ##
## RVB Left mouse click to "Skip Track" ##
## pyautogui.click(X, Y)

## NOTE: YOU WILL NEED TO ADD THE X and Y CO-ORDINANTS FOR "YOUR" SCREEN ON THE "CHAT BOX DATA ENTRY ##
## NOTE: ADD YOUR CHAT BOX TEXT ENTRY X Y CO-ORDS AT LINE 102 ##

## typewrite():
## You can automate typing of the string by using typewrite() function.
## Just pass the string which you want to type as an argument of this function.

## NOTE: MAKE A NEW FOLDER, ADD "resfresh" and "secrets"
## (ONLY "refresh_token", base_64 and "spotify_user_id" REQUIRED ##

## NOTE: FOR THIS EARLY VERSSION - GET SPOTTY PLAYING SOMETHING BEFORE RUNNING PLEASE ##

import json, requests, time, sys, os, pyautogui
from datetime import datetime
sys.path.insert(1, 'j:\\Spotty\secrets_and_database')
from does_pyautogui_secrets import spotify_user_id
from refresh import Refresh

temp = 'xxx'
flag = 0

os.system('cls')
print('ALL NEW NOW PLAYING: 02-06-2023')
print('Spotify user ' + spotify_user_id)
print('Very Basic RVRB Auto-pilot testing v1.0 : 02-06-2023')
print('')

refreshCaller = Refresh()

class NowPlaying:
    def __init__(self):
        self.user_id = spotify_user_id
        self.spotify_token = ''
        self.nowtrack = ''
        self.newtrack = ''
        self.artist = ''
        self.title = ''

    def get_now_playing_track(self):
        global temp, flag
        query = 'https://api.spotify.com/v1/me/player/currently-playing'
        response = requests.request('get', url=query, headers={'Content-type': 'application/json','Authorization': 'Bearer {}'.format(self.spotify_token)})
        
        if response.status_code == 204:
            if flag == 0:
                print('[X] NOTHING PLAYING [X]')
                temp = 'xxx'
                flag = 1
            time.sleep(45)
            self.call_refresh()
            return

        flag = 0
        json_data = json.loads(response.text)
        self.nowtrack = json_data['item']['uri']
        self.title = json_data['item']['name']

        ## print('CURRENT NOW PLAYING TRACK')
        ## print(self.title)

        if temp != self.nowtrack:
            prevtrack = temp
            temp = self.nowtrack 
            self.call_refresh()
            self.nowtrack = prevtrack
            ## print('[*NEW*] ' + self.title)

            ## NOTE: ADD YOUR CHAT BOX TEXT ENTRY X Y CO-ORDS HERE ##
            ## RVRB Show Artist ##
            pyautogui.click(1299, 820)      ## NOTE: MY "X" is "1299" and "Y" is "820" ##
            pyautogui.typewrite("/artist")
            pyautogui.typewrite(["enter"])
            pyautogui.moveTo(100, 200)      ## NOTE:  Reset mouse pointer X, Y (BLANK SPACE) ##

            ## NOTE: MORE BITS TO ADD LATER WATCH THIS ==> "     "  ##

        while True:
            time.sleep(30)
            self.get_now_playing_track()  

    def call_refresh(self):
        global refreshCaller
        while True:
            self.spotify_token = refreshCaller.refresh()
            if self.spotify_token == -1:   # NOTE: Check for '-1' returned from refresh class.
                print('[X] Error Refreshing Token - Retrying in 30 Secs [X]')
                time.sleep(30)
            else:
                break

a = NowPlaying()
a.call_refresh()
a.get_now_playing_track()
