import time
from pandas.core.frame import DataFrame  
#from googleapiclient.discovery import build                                
#from selenium import webdriver             
import chromedriver_binary 
from apiclient.discovery import build
import pandas as pd
import os

# path = './Kamoku'
# files = os.listdir(path)

# for i in files:


sub_title = pd.read_csv("線形代数２.csv", encoding = "cp932", header = None)
sub_list = sub_title.iloc[:,0]
#print(sub_list)

video_title_list = [[] for _ in range(len(sub_list))]
video_url_list =  [[] for _ in range(len(sub_list))]
video_id_list =  [[] for _ in range(len(sub_list))]

#APIは一日に使用できる制限があるため，制限が来たらプロジェクトを新しく作成し，そこで取得したAPIに切り替える
# api_key = "AIzaSyD0H1dkdyY_rhr7LWrxaAObNu4JrekaAmM"
#api_key = "AIzaSyD9W0DTv6J8QLfSKL8m4XCUtqXZ7N8rkwU"
#api_key = "AIzaSyB0HUZ6aQq9-5X84N4GKDcrUpcTWEa_VUc"
api_key ="AIzaSyD4VXelLpQqRjphQmPfj15B7-k6Vd6Hgtw"


for j in range(len(sub_list)):
    def get_videos_search(keyword):
        youtube = build('youtube', 'v3', developerKey=api_key)
        youtube_query = youtube.search().list(q=keyword, part='id,snippet', maxResults=20)
        youtube_res = youtube_query.execute()
        return youtube_res.get('items', [])

    result = get_videos_search(sub_list[j])
    for item in result:
        if item['id']['kind'] == 'youtube#video':
            video_title_list[j].append(item['snippet']['title'])
            video_url_list[j].append('https://www.youtube.com/watch?v=' + item['id']['videoId'])
            video_id_list[j].append('https://www.youtube.com/embed/' + item['id']['videoId'])
    #print("=================================================")

for j in range(len(sub_list)):
    #print(video_title_list[j])
    #print("===========================================================================")
    #print(video_url_list[j])
    df = pd.DataFrame({'Youtubetitel':video_title_list[j],'Youtubeurl':video_url_list[j],'Youtubeid':video_id_list[j]})
    #print("===========================================================================")
    df.to_csv(f'./Kyouzai/video_kyouzai{j}.csv', index = None, encoding = 'utf-8-sig')
