from datetime import datetime
from uuid import uuid4
import funcs
import config
import cv2
import os

directory = 'ready_for_upload/instagram'

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

    media_type = funcs.get_media_type(filename)
    if not media_type:
        print(f'Error determining media type for {filename}. Skipping...')
        return False

    post_type = funcs.determine_post_type(filepath)
    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_media_dimensions(filepath)
    
    duration = funcs.get_video_duration(filepath)

    if media_type == 'image':
        phash = funcs.generate_phash(filepath)
    elif media_type == 'video':
        try:
            thumb_path = generate_thumbnail(filepath)
            obj_storage.PutFile(thumb_path, f'thumbnails/{file_hash}.jpg') # this might be a problem in case of duplicate hashes
            thumbnail_url = f"https://storysave.b-cdn.net/thumbnails/{file_hash}.jpg"
            phash = funcs.generate_phash(thumb_path)
            os.remove(thumb_path)
        except:
            print('Error generating thumbnail. Skipping...')
            return False

    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, platform)

    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 generate_thumbnail(filepath):
    thumb_path = f'temp/{uuid4()}.jpg'
    cap = cv2.VideoCapture(filepath)
    ret, frame = cap.read()
    cv2.imwrite(thumb_path, frame)
    cap.release()
    return thumb_path

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 = []
    
    user_folders = os.listdir(folder_path)
    for user_folder in user_folders:
        user_folder_path = os.path.join(folder_path, user_folder)
        if not os.path.isdir(user_folder_path):
            continue
        files = os.listdir(user_folder_path)
        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 = config.get_storage()

    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.")