from BunnyCDN.Storage import Storage
import config, os, cv2
from concurrent.futures import ThreadPoolExecutor

# this script will take a screenshot of the first frame of each video and upload it as a thumbnail to BunnyCDN

obj_storage = Storage('345697f9-d9aa-4a6b-a5ec8bffc16d-ceaf-453e', 'storysave')

db, cursor = config.gen_connection()

cursor.execute("SELECT id, media_id, media_url FROM media WHERE media_type = 'video' AND thumbnail IS NULL and status = 'public';")
results = cursor.fetchall()

count = 0
print(f"Found {len(results)} files to process.")

cacheDir = 'cache'

def DownloadFile(serverPath, cacheDir):
    localFilePath = os.path.join(cacheDir, os.path.basename(serverPath))
    
    if os.path.exists(localFilePath):
        print(f"File already exists: {localFilePath}")
        return localFilePath
    
    obj_storage.DownloadFile(storage_path=serverPath, download_path=cacheDir)
    print(f"Downloaded {serverPath} to {localFilePath}")
    return localFilePath

def ImportMedias():
    with ThreadPoolExecutor(max_workers=10) as executor:
        for video in results:
            serverPath = video[2].replace("https://storysave.b-cdn.net/", '').replace('//', '/').replace('\\', '/')
            executor.submit(DownloadFile, serverPath, cacheDir)
    

for result in results:
    count += 1
    itemID = result[0]
    mediaID = result[1]
    mediaURL = result[2]
    extension = mediaURL.split('.')[-1]
    
    serverPath = result[2].replace("https://storysave.b-cdn.net/", '').replace('//', '/').replace('\\', '/')
    
    localFilePath = os.path.join(cacheDir, os.path.basename(serverPath))

    filePath = DownloadFile(serverPath, cacheDir)

    cap = cv2.VideoCapture(localFilePath)
    ret, frame = cap.read()
    cv2.imwrite('thumbnail.jpg', frame)
    cap.release()

    thumbnailURL = f"https://storysave.b-cdn.net/thumbnails/{itemID}.jpg"
    
    obj_storage.PutFile('thumbnail.jpg', f'thumbnails/{itemID}.jpg')
    

    cursor.execute("UPDATE media SET thumbnail = %s WHERE id = %s;", (thumbnailURL, itemID))
    db.commit()
    
    print(f"[{count}/{len(results)}] thumbnail: {thumbnailURL} {cursor.rowcount}")