import json
import operator
from functools import reduce

from flask import request
from median.models import WsclientError

from ressources.blueprint.transfert.transfertDTO import TransfertItemDTO, State


def get_all_request():
    data = json.loads(request.data)

    criterias = data.get('criterias', [])
    start = data.get('start', None)
    end = data.get('end', None)
    states = data.get('states', [])
    expr = True

    if start is not None:
        expr &= WsclientError.chrono >= start

    if end is not None:
        expr &= WsclientError.chrono <= end

    if len(states) == 1:
        expr &= WsclientError.delete if states[0] == State.Success.value else ~WsclientError.delete

    if len(criterias) > 0:
        lst = list(map(lambda s: (
            (WsclientError.function.contains(s.strip())) |
            (WsclientError.poste.contains(s.strip())) |
            (WsclientError.username.contains(s.strip()))
        ), criterias))
        search = reduce(operator.and_, lst)
        expr = reduce(operator.and_, [expr, search])

    return (WsclientError.select(WsclientError.pk.alias('pk'),
                                 WsclientError.chrono.alias('chrono'),
                                 WsclientError.username.alias('username'),
                                 WsclientError.function.alias('current_function'),
                                 WsclientError.poste.alias('poste'),
                                 WsclientError.nb_retry.alias('nb_retry'),
                                 WsclientError.is_delete.alias('delete'))
            .where(expr)
            .order_by(WsclientError.chrono.desc())
            ).objects()


def get_transfert_item(pk):

    transfert = WsclientError.get(pk=pk)

    dto = TransfertItemDTO(pk=transfert.pk, username=transfert.username,
                           function=transfert.function, poste=transfert.poste,
                           nb_retry=transfert.nb_retry, error_msg=transfert.error_msg,
                           delete=transfert.is_delete, params=transfert.param,
                           chrono=transfert.chrono, wsdl=transfert.wsdl,
                           url=transfert.url, retry_date=transfert.retry_date)

    dto.xml_params = transfert.param

    return json.loads(dto.toJson())
