from sqlalchemy import func

from app.main.data_model.games.finedge.fe_position import FEPosition
import app.main.util.helpers as helpers


class FEPositionRepository:

    def __init__(self, session):
        self.session = session

    def get_last_positions_by_portfolio_id(self, portfolio_id, filter_null):
        last_date = self.session.query(func.max(FEPosition.market_date)).filter(FEPosition.portfolio_id == portfolio_id)
        positions = self.session.query(FEPosition).filter(FEPosition.market_date == last_date,
                                                          FEPosition.portfolio_id == portfolio_id)
        if filter_null:
            positions = positions.filter(FEPosition.weight > helpers.FINEDGE_MIN_POSITION)
        positions = positions.all()
        if len(positions) == 0:
            return None
        return positions

