import json, requests
from refresh import Refresh

class CopyPlaylist:
    def __init__(self): 
        self.user_id = 'daftjoe'    # YOUR SPOTTY ID HERE
        # RVRB MIX-1 playlist as SOURCE.
        self.source_id = '2PJVVVL0nKUrdP5RA7VBt3'
        # RVRB Queue playlist as TARGET.
        self.target_id = '51xotsRpnXm8XEbCv1sa1E'
        self.spotify_token = ''
        self.tracks = ''

    def start_copy(self):
        print('COPY RVRB MIX-1 PLAYLIST TO RVRB QUEUE ~ v1.0 14 MAR 2023')

        # Clear current tracks from 'target' playlist.
        query = 'https://api.spotify.com/v1/playlists/{}/tracks?uris={}'.format(self.target_id, self.tracks)
        response = requests.request('put', url=query, headers={'Content-type': 'application/json','Authorization':'Bearer {}'.format(self.spotify_token)})
       
        print('Get total of tracks in SOURCE playlist:')
        query = "https://api.spotify.com/v1/playlists/{}".format(self.source_id)
        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"])
        print('Total tracks = ' + str(self.queue_total) + '.')

        for t in range(0, self.queue_total, 100):
            ## print('• Copying tracks: [' + str(t) + ']', end='\r')
            print('• Copying tracks...')
            self.tracks = ''
            self.offset = t

            query = 'https://api.spotify.com/v1/playlists/{}/tracks'.format(self.source_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()
            for i in response_json['items']:
                self.tracks += i['track']['uri'] + ','
            self.tracks = self.tracks[:-1]

            query = 'https://api.spotify.com/v1/playlists/{}/tracks?uris={}'.format(self.target_id, self.tracks)
            response = requests.request('post', url=query, headers={'Content-type': 'application/json','Authorization':'Bearer {}'.format(self.spotify_token)})
        print('')
        print('• Completed...')

    def call_refresh(self):
        refreshCaller = Refresh()
        self.spotify_token = refreshCaller.refresh()
        self.start_copy()

a = CopyPlaylist()
a.call_refresh()
