import os
import logging

from django.conf import settings

from .models import Video, READY, FAIL
from .s3_uploader import upload_file
from .utils import (
    add_video_to_playlist,
    generate_thumbnail,
    download_file,
    get_video_duration,
)

from cp_video.celery import app
from cp_video.utils import asset_upload

log = logging.getLogger('send_video_to_s3')


@app.task()
def send_video_to_s3(video_id=None):
    if not video_id:
        return
    
    log.info(f'Uploading video id {video_id} to S3...')
    local_video = Video.objects.get(id=video_id)

    try:
        video_name = local_video.local_file.name.split('/')[-1]
        key = asset_upload(local_video, video_name)
        file_path = settings.DOMAIN_NAME + settings.MEDIA_URL + key
        log.info(f'File path: {file_path}')

        video_file = download_file(file_path)

        local_video.local_file = None
        local_video.status = READY
        local_video.s3_file = upload_file(video_file, key, 'video/mp4')
        # local_video.duration = get_video_duration(video_name)

        try:
            log.info('Generating thumbnail...')
            thumbnail, thumbnail_name = generate_thumbnail(file_path, video_name)
            key_thumbnail = f'videos/thumbnail/{thumbnail_name}'
            local_video.thumbnail = upload_file(thumbnail, key_thumbnail, 'image/jpeg')
            log.info('Thumbnail generated successfully!')
        except Exception as e:
            log.error(e)
            log.info('Thumbnail generation failed!')

        local_video.save()

        log.info(f'Video id {local_video.id} uploaded to S3...')

        add_video_to_playlist(local_video)
        os.remove(video_file.name)

    except Exception as e:
        log.error(e)
        local_video.status = FAIL
        local_video.save(update_fields=['status'])
        log.info(f'Video {video_id} upload failed!')