from sqlalchemy.orm import Session
from sqlalchemy import and_

from app.model.bussiness_model import ProjectLabel as plModel
from app.model.schemas.project_label_schemas import ProjectLabel


def get_label_list(project_id: int, session: Session):
    """
    根绝项目id获取标签列表
    :param project_id: 项目id
    :param session:
    :return:
    """
    label_list = session.query(plModel).filter(plModel.project_id == project_id).all()
    label_list = [ProjectLabel.from_orm(label).dict() for label in label_list]
    return label_list


def get_label_for_train(project_id: int, session: Session):
    id_list = []
    name_list = []
    label_list = session.query(plModel).filter(plModel.project_id == project_id).order_by(plModel.id).all()
    for label in label_list:
        id_list.append(label.id)
        name_list.append(label.label_name)
    return id_list, name_list


def add_label(label: plModel, session: Session):
    """
    新增标签
    :param label:
    :param session:
    :return:
    """
    session.add(label)
    session.commit()
    return label.id


def check_label_name(project_id: int, label_name: str, session: Session, label_id: int = None):
    """
    检验标签名称是否存在
    :param label_id:
    :param project_id: 项目id
    :param label_name: 标签名称
    :param session:
    :return:
    """
    query = session.query(plModel)
    filters = [plModel.project_id == project_id, plModel.label_name == label_name]
    if label_id is not None:
        filters.append(plModel.id != label_id)
    query = query.filter(and_(*filters))
    count = query.count()
    if count > 0:
        return True
    else:
        return False


def update_label(label: plModel, session: Session):
    """
    修改标签名称
    :param label:
    :param session:
    :return:
    """
    session.query(plModel).filter_by(id=label.id).update({
        "label_name": label.label_name,
        "meta": label.meta
    })
    session.commit()


def del_label(label_id: str, session: Session):
    """
    根据标签id删除标签
    :param label_id: 标签id
    :param session:
    :return:
    """
    row_del = session.query(plModel).filter_by(id=label_id).delete()
    session.commit()
    return row_del
