import requests
from datetime import datetime
import calendar

def search(what, type, api_key):
    url = "https://www.googleapis.com/youtube/v3/search?part=snippet&q=%s&type=%s&key=%s" % (what, type, api_key)
    r = requests.get(url)
    return r.json()

def playlistItems(playlistId, api_key, all=False, nextToken=None):
        videos = []
        info_url = "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50&playlistId=%s&key=%s" % (
            playlistId,
            api_key
        )

        if nextToken is not None:
            info_url += "&pageToken=%s" % (nextToken)

        request_data = requests.get(info_url)

        request_data_json = request_data.json()

        videos += parseRequestData(request_data_json)
        if all == True and 'nextPageToken' in request_data_json:
            videos += playlistItems(playlistId, api_key, request_data_json['nextPageToken'])

        return videos
            
            

def parseRequestData(request_data_json):
        parsed_videos = []
        for element in request_data_json['items']:
            video = {}
            videotime = datetime.strptime(element['snippet']['publishedAt'][:-5], "%Y-%m-%dT%H:%M:%S")
            timestamp = calendar.timegm(videotime.utctimetuple())
            video['timestamp'] = int(timestamp)
            video['videoid'] = element['snippet']['resourceId']['videoId']
            video['title'] = element['snippet']['title']
            video['channel_id'] = element['snippet']['channelId']
            video['nick'] = element['snippet']['channelTitle']
            parsed_videos.append(video)

        return parsed_videos            
            

            