import os

import google_auth_oauthlib.flow
import googleapiclient.discovery
import youtube_dl


class Song(object):
    def __init__(self, artist, track):
        self.artist=artist
        self.track=track


class Playlist(object):
    def __init__(self, id, title):
        self.id = id
        self.title = title


class YoutubeClient(object):
    def __init__(self, credentials):
        scopes = ["https://www.googleapis.com/auth/youtube.readonly"]
        # Disable OAuthlib's HTTPS verification when running locally.
        # *DO NOT* leave this option enabled in production.
        os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"

        api_service_name = "youtube"
        api_version = "v3"
        client_secrets_file = credentials

        # Get credentials and create an API client
        flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(
            client_secrets_file, scopes)
        credentials = flow.run_console()
        youtube = googleapiclient.discovery.build(
            api_service_name, api_version, credentials=credentials)

        self.youtube_client = youtube_client

    def get_youtube_playlists(self):
        request = self.youtube_client.playlists().list(
            part="id, snippet",
            maxResults=10,
            mine=True
        )
        response = request.execute()

        playlists = [Playlist(item['id'], item['snippet']['title']) for item in response['items']] # get all playlists

        return playlists

    def get_playlist_vids(self, playlist_id):
        songs = []
        request = self.youtube_client.playlistItems().list(
            part="id, snippet",
            playlistId=playlist_id
        )
        response = request.execute()

        for item in response['items']:
            video_id = item['snippet']['resourceId']['videoId']
            artist, track = self.get_vid_details(video_id)
            if artist and track:
                songs.append(Song(artist, track))

        return songs

    def get_vid_details(self, video_id):
        url = f"https://www.youtube.com/watch?v={video_id}"

        vid = youtube_dl.YoutubeDL({'quiet': True}).extract_info(
            url, download=False
        )
        artist = vid['artist']
        track = vid['track']

        return artist, track
