from typing import Optional

from fastapi import Query

from watcher.db import BaseModel


def get_order_by_params(order_by: Optional[str] = Query(None)) -> Optional[list]:
    if order_by:
        order_by = order_by.split(',')
    return order_by


def prepare_order_by_params(model: BaseModel, ordering: tuple, is_reverse: Optional[bool] = False) -> list:
    order_up, order_down = 'asc', 'desc'
    if is_reverse:
        order_up, order_down = order_down, order_up

    order_params = []
    for order_field in ordering:
        order = order_up
        if order_field.startswith('-'):
            order = order_down
            order_field = order_field[1:]

        order_params.append(
            getattr(getattr(model, order_field), order)()
        )
    return order_params
