from datetime import datetime
import uuid

from sqlalchemy.orm import Session

from src.core.log_conf import logger
from src.db.models.media import MediaActor
from src.db.repository.media.actorfile import delete_mediaactorfile
from src.schema.media.actor import MediaActorModel


def create_new_mediaactor(new_actor: MediaActorModel, db: Session) -> MediaActor:
    logger.info(f"create MediaActor with url {new_actor.url}")
    media_actor: MediaActor = MediaActor()
    media_actor.id = str(uuid.uuid4())
    if new_actor.name is not None:
        media_actor.name = new_actor.name
    media_actor.url = new_actor.url
    media_actor.created_date = datetime.now()
    media_actor.last_modified_date = datetime.now()
    media_actor.version = 0
    db.add(media_actor)
    db.commit()
    db.refresh(media_actor)
    logger.info(f"created {media_actor}")
    return media_actor

def delete_mediaactor(db: Session, actor_id: str):
    logger.info(f"delete MediaActor with id {actor_id}")
    media_actor = db.get(MediaActor, actor_id)
    if media_actor is not None:
        actor_files = media_actor.media_actor_files
        for actor_file in actor_files:
            delete_mediaactorfile(db, actorfile_id=actor_file.id)
    db.refresh(media_actor)
    db.delete(media_actor)
    db.commit()

def import_mediaactor(db: Session, new_actor: MediaActorModel) -> MediaActor:
    """
    import MediaFile and set missing values with default ones.
    """
    logger.info("import MediaActor with %s", new_actor)
    media_actor: MediaActor = MediaActor()
    media_actor.id = new_actor.id
    if new_actor.created_date:
        media_actor.created_date = new_actor.created_date
    else:
        media_actor.created_date = datetime.now()
    if new_actor.last_modified_date:
        media_actor.last_modified_date = new_actor.last_modified_date
    else:
        media_actor.last_modified_date = datetime.now()
    media_actor.version = new_actor.version
    if new_actor.name:
        media_actor.name = new_actor.name
    else:
        media_actor.name = ""
    if new_actor.url:
        media_actor.url = new_actor.url
    else:
        media_actor.url = ""
    db.add(media_actor)
    db.commit()
    db.refresh(media_actor)
    return media_actor
