from BunnyCDN.Storage import Storage
import config, os, funcs
from PIL import Image

# the hash of the images are different due to optimizer

#obj_storage = Storage('577cb82d-8176-4ccf-935ce0a574bf-fe4c-4012', 'altpins')
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 width = 0;")
results = cursor.fetchall()

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

cacheDir = 'cache'
for result in results:
    count += 1
    videoID = 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))
    
    if os.path.exists(localFilePath):
        print(f"File already exists: {localFilePath}")
    else:
        obj_storage.DownloadFile(storage_path=serverPath, download_path=cacheDir)

    mediaType = funcs.get_media_type(localFilePath)

    if mediaType == 'image':
        with Image.open(localFilePath) as img:
            width, height = img.size
    elif mediaType == 'video':
        width, height = funcs.get_video_dimensions(localFilePath)
            

    cursor.execute("UPDATE media SET width = %s, height=%s WHERE id = %s;", (width, height, videoID))
    db.commit()

    print(f"[{count}/{len(results)}] width: {width}, height: {height} {cursor.rowcount}")