from datetime import datetime
import uuid

from sqlalchemy.orm import Session

from src.core.log_conf import logger
from src.db.models.media import MediaFile
from src.schema.media.file import MediaFileModel


def create_new_mediafile(link: str, db: Session) -> MediaFile:
    """
    Create MediaFile with gievne URL.
    """
    logger.info("create MediaFile with url {link}")
    media_file: MediaFile = MediaFile()
    media_file.id = str(uuid.uuid4())
    media_file.url = link
    media_file.created_date = datetime.now()
    media_file.last_modified_date = datetime.now()
    media_file.version = 0
    media_file.review = True
    media_file.should_download = True
    db.add(media_file)
    db.commit()
    db.refresh(media_file)
    logger.info("created %s", media_file)
    return media_file


def delete_mediafile(db: Session, media_file_id: str):
    """
    Delete MediaFile with given ID from db.
    """
    logger.info("delete MediaFile with id %s", media_file_id)
    media_file = db.get(MediaFile, media_file_id)
    db.delete(media_file)
    db.commit()


def import_mediafile(db: Session, new_file: MediaFileModel) -> MediaFile:
    """
    import MediaActor and set missing values with defautl ones.
    """
    logger.info("import MediaFile with %s", new_file)
    media_file: MediaFile = MediaFile()
    media_file.id = new_file.id
    if new_file.created_date:
        media_file.created_date = new_file.created_date
    else:
        media_file.created_date = datetime.now()
    if new_file.last_modified_date:
        media_file.last_modified_date = new_file.last_modified_date
    else:
        media_file.last_modified_date = datetime.now()
    media_file.version = new_file.version
    if new_file.title:
        media_file.title = new_file.title
    else:
        media_file.title = ""
    if new_file.file_name:
        media_file.file_name = new_file.file_name
    else:
        media_file.file_name = ""
    if new_file.cloud_link:
        media_file.cloud_link = new_file.cloud_link
    else:
        media_file.cloud_link = ""
    if new_file.url:
        media_file.url = new_file.url
    else:
        media_file.url = ""
    media_file.review = new_file.review
    media_file.should_download = new_file.should_download
    db.add(media_file)
    db.commit()
    db.refresh(media_file)
    return media_file
