import json
import operator
from functools import reduce

from flask import request
from median.constant import EcoType, EtatListe
from median.models import Magasin, FListe


def get_replenish_list():
    data = json.loads(request.data)
    criterias = data.get('criterias')

    andexpr = Magasin.eco_type == EcoType.Externe.value

    if len(criterias) > 0:
        lst = list(map(lambda s: (
            (FListe.liste.contains(s.strip())) |
            (Magasin.libelle.contains(s.strip()))
        ), criterias))

        search = reduce(operator.and_, lst)

        expr = reduce(operator.and_, [andexpr, search])
    else:
        expr = andexpr

    lis = (FListe.select(FListe.pk.alias('pk'),
                         FListe.liste.alias('liste'),
                         FListe.zone_fin.alias('equipment_mag'),
                         Magasin.pk.alias('equipment_pk'),
                         Magasin.libelle.alias('equipment_label'),
                         Magasin.avatar.alias('equipment_avatar'),
                         FListe.date_creation,
                         )
           .where((FListe.mode == 'E') & (FListe.zone_deb == '') & (FListe.etat == EtatListe.Vierge.value))
           .join(Magasin, on=FListe.zone_fin == Magasin.type_mag)
           .where(expr))
    return lis
