from sqlalchemy import and_
from sqlalchemy.orm import Session
from libs.functions import wrapper_out
from models.margin import GuildMargin


@wrapper_out()
def get_margin(db: Session, param):
    guild_filters = []
    if param.guild_id:
        guild_filters.append(GuildMargin.guild_id == param.guild_id)
    if param.status:
        guild_filters.append(GuildMargin.status == param.status)
    if param.start_time:
        guild_filters.append(GuildMargin.create_time >= param.start_time)
    if param.end_time:
        guild_filters.append(GuildMargin.create_time <= param.end_time)
    if not guild_filters:
        query_res = db.query(GuildMargin).all()
        return [i.to_dict() for i in query_res][::-1]
    else:
        get_user_orm_sql = db.query(GuildMargin).filter(and_(*guild_filters))
        query_res = db.execute(get_user_orm_sql).fetchall()
    return [i[0].to_dict() for i in query_res][::-1]
