

from __future__ import print_function
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google.oauth2 import service_account
import argparse
import requests
import pprint
import json
import calendar
import time
import os
import shutil
from distutils.util import strtobool

SCOPES = ['https://www.googleapis.com/auth/presentations.readonly',
          'https://www.googleapis.com/auth/drive.metadata.readonly']

dir_sound = 'mp3_track/'
dir_photo = 'photo/'
dir_text = 'text_file/'
dir_video = 'video_material/'
dir_title = 'title/'
dir_subtitle = 'subtitle/'
dir_anchor = 'anchor_raw/'
tmp_video_dir = 'tmp_video/'
video_sub_folder = 'ai_anchor_video/'

def parse_url(url):
    #https://docs.google.com/presentation/d/17jJ3OZWh8WorFcolB_LiTa7xQ3R-xrmFlqJ_EyCj06M/edit#slide=id.p
    return url.split('/')[5]

def parse_slide_url(slide_url,eng):
    PRESENTATION_ID = parse_url(slide_url)
    credentials = service_account.Credentials.from_service_account_file('spread2.json')
    scoped_credentials = credentials.with_scopes(SCOPES)
    creds = credentials

    notes_list=[]
    sub_title_list=[]
    img_list=[]

    service = build('slides', 'v1', credentials=creds)
        # Call the Slides API
    presentation = service.presentations().get(
        presentationId=PRESENTATION_ID).execute()
    slides = presentation.get('slides')
        
    for i, slide in enumerate(slides):
        # Check if the notes exists
        if 'text' in slide['slideProperties']['notesPage']['pageElements'][1]['shape'].keys():
            notes = slide['slideProperties']['notesPage']['pageElements'][1]['shape']['text']['textElements'][1]['textRun']['content']
            if '[sub_title]' in notes:
                sub_title = notes.split('[sub_title]')[1].strip()
                print('Sub_title:',end='')
                pprint.pprint(sub_title)
                sub_title_list.append(sub_title)
                notes = notes.split('[sub_title]')[0].strip()
            pprint.pprint(notes)
            notes_list.append(notes)  
        else:
            notes_list.append("")
                
        # Convert the content of the presentation to png
        thumbnail = service.presentations().pages().getThumbnail(presentationId=PRESENTATION_ID, pageObjectId=slide['objectId']).execute()
        pprint.pprint(thumbnail)
        img_list.append(thumbnail['contentUrl'])
            
    # data
    slide_content = { "name": presentation['title'], "text_content": notes_list, "image_urls": img_list, "avatar": "7", "client_id": calendar.timegm(time.gmtime()) }
    if eng:
        slide_content['sub_titles'] = sub_title_list
    print(slide_content)
    return slide_content['name'],slide_content['text_content'],slide_content['image_urls']
        