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

directory = 'ready_to_upload/'

def UploadMedia(username, user_id, filepath):
    thumbnail_url = None
    phash = None
        
    filename = os.path.basename(filepath)
    file_extension = os.path.splitext(filename)[1].lower()

    media_type = funcs.get_media_type(filename)

    post_type = funcs.determine_post_type(filepath, media_type)
    if not post_type:
        print(f'Error determining post type for {filename}. Skipping...')
        return False

    file_hash = funcs.calculate_file_hash(filepath)

    post_date = datetime.now()

    width, height = funcs.get_video_dimensions(filepath) if media_type == 'video' else Image.open(filepath).size
    
    duration = funcs.get_video_duration(filepath) if media_type == 'video' else 0 # slower

    if media_type == 'video':
        try:
            thumbPath = f'temp/{file_hash}.jpg'
            cap = cv2.VideoCapture(filepath)
            ret, frame = cap.read()
            cv2.imwrite(thumbPath, frame)
            cap.release()
            obj_storage.PutFile(thumbPath, f'thumbnails/{file_hash}.jpg') # slower
            thumbnail_url = f"https://storysave.b-cdn.net/thumbnails/{file_hash}.jpg"
            phash = funcs.generate_phash(thumbPath)
            os.remove(thumbPath)
        except:
            print('Error generating thumbnail. Skipping...')
            return False
    elif media_type == 'image':
        phash = funcs.generate_phash(filepath)

    newFilename = f'{file_hash}{file_extension}'
    server_path = f'media/{post_type}/{username}/{newFilename}'

    file_url = f"https://storysave.b-cdn.net/{server_path}"

    obj_storage.PutFile(filepath, server_path) # slow as fuck

    post_type = 'story' if post_type == 'stories' else 'post'
    query = "INSERT IGNORE INTO media (username, media_type, media_url, width, height, post_type, date, user_id, hash, filename, duration, thumbnail, phash, platform) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"
    values = (username, media_type, file_url, width, height, post_type, post_date, user_id, file_hash, filename, duration, thumbnail_url, phash, 'instagram')

    newCursor.execute(query, values) # slower
    newDB.commit()
    print(f'[{newCursor.rowcount}] records updated. File {filename} uploaded to {file_url}')

    os.remove(filepath)

    return True

def get_user_id(username):
    username = username.lower()
    if username in existing_users:
        return existing_users[username]
    
    return None

def get_media(folder_path):
    medias = []
    
    for user_folder in os.listdir(folder_path):
        files = os.listdir(os.path.join(folder_path, user_folder))
        for filename in files:
            filepath = os.path.join(folder_path, user_folder, filename)
            media = {
                'username': user_folder,
                'filepath': filepath,
                'user_id': get_user_id(user_folder)
            }
            
            medias.append(media)
                
    return medias

def dump_instagram(folder_path):
    medias = get_media(folder_path)

    for media in medias:
        UploadMedia(media['username'], media['user_id'], media['filepath'])
 

if __name__ == '__main__':
    print('Starting processing...')

    newDB, newCursor = config.gen_connection()

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

    newCursor.execute("SELECT DISTINCT username, user_id FROM media WHERE user_id IS NOT NULL")
    existing_users = {user[0].lower(): user[1].lower() for user in newCursor.fetchall()}
    
    dump_instagram(directory)

    print("Processing completed.")