#check to see if any channel has uploaded a new video. if it has program will tell the user and promp for which channel it would like to go to.
#once the user has slected a channel it will automatic go to the newest video of that channel

from googleapiclient.discovery import build #imports the script to work with youtube api
import webbrowser #allows you to use a web browser
import time #allows for delay
import RPi.GPIO as GPIO # allows axis to the gpio ports. can call it with the short hand GPIO
GPIO.setmode(GPIO.BOARD) #now able to call pins by there numerical position (defalt is in Boardcom SOC)
GPIO.setwarnings(False) #turns off warnings when using pins
bt = [11,13,15,29,31,33]#the pins for all the buttons (numbered by physical location)
led=[3,5,7,19,21,23] #the pins for all the leds (numbered by physical location)

for i in range(0,len(led)):# used to set the IO
    GPIO.setup(led[i],GPIO.OUT)#sets all led pins as outputs
    GPIO.setup(bt[i], GPIO.IN,pull_up_down = GPIO.PUD_UP)#lets all button pins as outputs
    GPIO.output(led[i],False) # if for some reason an led was still on this will reset it to off

api_key = '' #this is where your api key goes
youtube = build('youtube', 'v3', developerKey=api_key) #enables use of api
channels =['Jeremy Jahns','Kitboga','penguinz0','PewDiePie','Videogamedunky','Good Mythical Morning']#string names of channels
ID=['UC7v3-2K1N84V67IF-WTRG-Q','UCm22FAXZMw1BaWeFszZxUKw','UCq6VFHwMzcMXbuKyG7SQYIg','UC-lHJZR3Gqxm24_Vd_AJ5Yw','UCsvn_Po0SmunchJYOWpOxMg','UC4PooiX37Pld1T8J5SYT-SQ'] #the id of the channel used for searching
video_Id=['','','','','',''] #needs to be an array to save the video id which will be used to give us the url
videoURL = 'https://www.youtube.com/watch?v='#will need to add the video id to get the full url
goto_channel=0 #need to be set to something when the keyboard is not in use inorder of the porgram to move forward if not using the input statment 
while True:
    for count in range(0,6):#need to get the data form all 6 channels befor giving user a pormpt
        video_count= open("upload_count.txt","r")#opens the saved video count of comparison
        data= video_count.read().splitlines()#loads the data into an array
        request = youtube.channels().list(id=ID[count],part='contentDetails, statistics')#selecting the channel data to retrieve  
        response = request.execute()#retrieving the data 
        for items in response['items']:#serching through the response
            totaluploads_pl= items['contentDetails']['relatedPlaylists']['uploads'] #this is the id of the total uploads playlist
            total_videos= items['statistics']['videoCount'] #number of total uploads
        request = youtube.playlistItems().list(part='contentDetails',playlistId = totaluploads_pl)#slecting the playlist data to retrieve        
        response = request.execute()#retrieving the data
        for items in response['items']:
            video_Id[count] = (items['contentDetails']['videoId']) # location of the videoId items{contentDetails(videoId)}
            break #there is more than one video id in items['contentDetails']['videoId'] we only want the first one so we need to break the loop befor is saves the next one to video id
        if(data[count]<total_videos):#compairs the total uploads of the channel to the saved count
            print('new upload from ' + channels[count])#states who has uploaded
            GPIO.output(led[count],True)# turns on led associated with channel
            data[count]= total_videos
        video_count.close()#closes the read only txtfile

        #Updating the txt file
        video_count= open("upload_count.txt","w")#reopen the txtfile in writing mode
        for i in range(0, len(data)):#updates the number of uploaded videos
           # print(data[i]) #print the vodeo count in console
            video_count.write(data[i])#puts the new count into the file. it automatically writes over the existing data
            video_count.write('\n') #moves to next line
        video_count.close()#closes the write only txt file

    #user input
    print ('enter to go to channel')
    print('1: '+channels[0] + ' 2: ' +channels[1] + ' 3: '+channels[2]+ ' 4: ' +channels[3]+ ' 5: ' + channels[4] + ' 6: '+ channels[5] + ' 0: None Reloop' )#displaying options
   
   # goto_channel = input('chose:')#gets user input for which channel to go to
    start_time=time.time()#looks at the current time
    seconds=5 *60 #how long we want to to wate before calling the api again 
    while True:# wates for however many seconds to pass
        current_time= time.time() #current time for comparison
        elapsed_time = current_time - start_time# counts the seconds that have passed
        if elapsed_time> seconds:#seeing to see if enough time has passed to leave the loop
            break#leave the time loop and recalls the api
    
        if(goto_channel=='1' or GPIO.input(bt[0]) ==False): #ckecks if button was pressed the raspberry pi uses internal pull ups so when no button is pressed it is high (ture) so when the button is pressed it becomes low (false)
            GPIO.output(led[0],False) #turns  off the led 
            webbrowser.open(videoURL + video_Id[0])#opens the newest video
            time.sleep(3)#if the button was pressed it will only be pressed once then pause to give time to get off the button to avoid opening the page several times
        
        elif(goto_channel=='2' or GPIO.input(bt[1]) ==False):
            GPIO.output(led[1],False) #turns  off the led 
            webbrowser.open(videoURL + video_Id[1])
            time.sleep(3)
        
        elif(goto_channel=='3' or GPIO.input(bt[2]) ==False):
            GPIO.output(led[2],False) #turns  off the led 
            webbrowser.open(videoURL + video_Id[2])
            time.sleep(3)
        
        elif(goto_channel=='4' or GPIO.input(bt[3]) ==False):
            GPIO.output(led[3],False) #turns  off the led 
            webbrowser.open(videoURL + video_Id[3])
            time.sleep(3)
        
        elif(goto_channel=='5' or GPIO.input(bt[4]) ==False):
            GPIO.output(led[4],False) #turns  off the led 
            webbrowser.open(videoURL + video_Id[4])
            time.sleep(3)
        
        elif(goto_channel=='6' or GPIO.input(bt[5]) ==False):
            GPIO.output(led[5],False) #turns  off the led 
            webbrowser.open(videoURL + video_Id[5])
            time.sleep(3)
        #else:
            #print('reloop')
