import os
import io
from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build
from googleapiclient.http import MediaIoBaseDownload

def get_drive_service():
    creds = Credentials.from_authorized_user_file('token.json')
    return build('drive', 'v3', credentials=creds)

def download_videos_from_folder(folder_id, download_path='downloads'):
    if not os.path.exists(download_path):
        os.makedirs(download_path)
    
    service = get_drive_service()
    
    # Query for files in the folder (specifically MP4)
    query = f"'{folder_id}' in parents and mimeType='video/mp4' and trashed=false"
    results = service.files().list(q=query, fields="nextPageToken, files(id, name)").execute()
    items = results.get('files', [])

    if not items:
        print('Không tìm thấy file mp4 nào trong thư mục này.')
        return []

    downloaded_files = []
    print(f'Tìm thấy {len(items)} tập phim. Đang tiến hành tải...')
    for item in items:
        file_id = item['id']
        file_name = item['name']
        file_path = os.path.join(download_path, file_name)
        
        # Bỏ qua nếu đã tải
        if os.path.exists(file_path):
            print(f"Đã tồn tại {file_name}, bỏ qua tải xuống.")
            downloaded_files.append(file_path)
            continue
            
        print(f'Đang tải: {file_name}')
        request = service.files().get_media(fileId=file_id)
        fh = io.FileIO(file_path, 'wb')
        downloader = MediaIoBaseDownload(fh, request)
        done = False
        while done is False:
            status, done = downloader.next_chunk()
            print(f"Tiến độ {file_name}: {int(status.progress() * 100)}%")
            
        downloaded_files.append(file_path)
    
    return downloaded_files

if __name__ == '__main__':
    folder_id = '1h8Nsh4j8vrqf956rnx78ENnWBMJxpDTc'
    download_videos_from_folder(folder_id)
