from flask import url_for
from app import photos, uploaded_files, aws_worker_session
from PIL import Image
import os
import time
import uuid
from app.dymodels import UserImage, UserFile
from flask_login import current_user
from datetime import datetime

"""
This module processes images and general files, generate uuid as unique file names, 
create thumbnails, then upload the image on Amazon S3.
"""


def process_profile_photo(form, data, basename):
    """Preprocesses the profile photo, save on Amazon S3, update the DynamoDB module.

    data: the image file
    basename: the original file name of the image
    """
    _, file_extension = os.path.splitext(basename)
    file_extension = file_extension.lower()

    # USING uuid1 to ensure mutiprocessing safe uuid generate.
    base_filename = uuid.uuid1().hex + file_extension

    profile_photo_filename = photos.save(data, name=base_filename, folder='all')
    profile_photo_filepath = photos.path(profile_photo_filename)

    aws_worker_session.upload_file_to_s3(profile_photo_filepath,
                                         '1779a3profileimage',
                                         profile_photo_filename,
                                         ACL='public-read')

    current_user.image_filename = profile_photo_filename
    current_user.image_url = aws_worker_session.get_object_url(
        '1779a3profileimage', profile_photo_filename)

    os.remove(profile_photo_filepath)

    return True


def process_files(form, data, name):
    """Preprocesses the image, create thumnails, 
    save on Amazon S3, update the DynamoDB module.

    data: the image
    name: the original file name
    """
    original_filename = name
    _, file_extension = os.path.splitext(original_filename)
    file_extension = file_extension.lower()

    # USING uuid1 to ensure multi-processing safe uuid generate.
    uuid_gen = uuid.uuid1()
    base_filename = uuid_gen.hex + file_extension
    original_filename = uploaded_files.save(data, name=base_filename,
                                            folder='original')
    original_filepath = uploaded_files.path(original_filename)
    thumbnail_filename = create_thumbnail(original_filepath, base_filename)

    thumbnail_filepath = uploaded_files.path(thumbnail_filename)

    aws_worker_session.upload_file_to_s3(original_filepath, '1779a3file',
                                         original_filename)
    aws_worker_session.upload_file_to_s3(thumbnail_filepath, '1779a3file',
                                         thumbnail_filename)

    post = UserImage(id=str(uuid_gen.int),
                     title=form.body.data,
                     author_id=current_user.id,
                     original_filename=original_filename,
                     base_filename=base_filename,
                     thumbnail_filename=thumbnail_filename,
                     timestamp=datetime.now(),
                     )

    post.save()

    os.remove(original_filepath)
    os.remove(thumbnail_filepath)

    return True


def create_thumbnail(img_path, base_name):
    """Creates a 300x300 thumbnail for the image and save on Amazon S3.

    img_path: path of the image ready to be processed
    base_name: the unique file name generated by uuid
    """
    image = Image.open(img_path)
    image.thumbnail((300, 300))
    path = uploaded_files.save(image, folder='thumbnail', name=base_name)
    image.close()
    return path


def process_files_general(form, data, name):
    """Preprocesses general files, save on Amazon S3, update the DynamoDB module.

    data: the general file
    name: the original file name of the image
    """
    original_filename = name
    _, file_extension = os.path.splitext(original_filename)
    file_extension = file_extension.lower()

    # USING uuid1 to ensure multi-processing safe uuid generate.
    uuid_gen = uuid.uuid1()
    base_filename = uuid_gen.hex + file_extension
    original_filename = uploaded_files.save(data, name=base_filename,
                                            folder='user_files')
    original_filepath = uploaded_files.path(original_filename)

    aws_worker_session.upload_file_to_s3(original_filepath, '1779a3file',
                                         original_filename)

    if current_user.is_anonymous:
        current_user.id = -1
        current_user.username = "__anonymous__"

    post = UserFile(id=str(uuid_gen.int),
                     author_id=current_user.id,
                     author = current_user.username,
                     s3_filename = original_filename,
                     original_filename = name,
                     timestamp=datetime.now(),
                     )

    post.save()
    os.remove(original_filepath)

    return aws_worker_session.get_object_download_url('1779a3file', original_filename, name)
