from datetime import datetime
import uuid

from sqlalchemy.orm import Session

from src.core.log_conf import logger
from src.db.models.media import MediaActorFile
from src.schema.media.actorfile import MediaActorFileModel


def create_new_mediaactorfile(
    db: Session, actor_id: str, file_id: str
) -> MediaActorFile:
    """
    Create relation for MediaFile and MediaActor
    """
    logger.info("create MediaActorFile with actor %s and file %s", actor_id, file_id)
    media_actor_file: MediaActorFile = MediaActorFile()
    media_actor_file.id = str(uuid.uuid4())
    media_actor_file.created_date = datetime.now()
    media_actor_file.last_modified_date = datetime.now()
    media_actor_file.version = 0
    media_actor_file.media_actor_id = actor_id
    media_actor_file.media_file_id = file_id
    db.add(media_actor_file)
    db.commit()
    db.refresh(media_actor_file)
    return media_actor_file


def delete_mediaactorfile(db: Session, actorfile_id: str):
    """
    Delete relation between MediaFile and MediaActor.
    """
    logger.info("delete MediaActorFile with id %s", actorfile_id)
    media_actorfile = db.get(MediaActorFile, actorfile_id)
    db.delete(media_actorfile)
    db.commit()


def import_mediaactorfile(
    db: Session, new_actorfile: MediaActorFileModel
) -> MediaActorFile:
    """
    Import MediaFile and set missing values with default ones.
    """
    logger.info("import MediaActorFile with %s", new_actorfile)
    media_actor_file: MediaActorFile = MediaActorFile()
    media_actor_file.id = new_actorfile.id
    if new_actorfile.created_date:
        media_actor_file.created_date = new_actorfile.created_date
    else:
        media_actor_file.created_date = datetime.now()
    if new_actorfile.last_modified_date:
        media_actor_file.last_modified_date = new_actorfile.last_modified_date
    else:
        media_actor_file.last_modified_date = datetime.now()
    media_actor_file.version = new_actorfile.version
    media_actor_file.media_actor_id = new_actorfile.media_actor_id
    media_actor_file.media_file_id = new_actorfile.media_file_id
    db.add(media_actor_file)
    db.commit()
    db.refresh(media_actor_file)
    return media_actor_file
