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

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(results):
    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)


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 file_size = 0;")
results = cursor.fetchall()

cacheDir = 'cache'

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

ImportMedias(results)