from .auth import auth
from ..db.models import Test, Datum, TestDatum, ChildDatum
from sqlalchemy import or_


@auth()
def search(auth_user, body):
    q = body.get('query')  # at this point q is guaranteed to be 2+char string

    results = {'tests': [], 'data': []}

    seen_obj_ids = []

    def check_obj_uniqueness(obj):
        if obj.id in seen_obj_ids:
            return False
        seen_obj_ids.append(obj.id)
        return True

    if body.get('type') in ['ALL', 'TESTS']:
        tests = Test.query.filter(Test.name.contains(q, autoescape=True)).all()
        tds = TestDatum.query.filter(TestDatum.label.contains(q, autoescape=True)).all()
        tests += list(map(lambda td: td.test, tds))
        tests = list(filter(check_obj_uniqueness, tests))

        results['tests'] = list(map(lambda test: test.to_obj(whos_asking=auth_user), tests))

    seen_obj_ids = []
    if body.get('type') in ['ALL', 'DATA']:
        data = Datum.query.filter(or_(
            Datum.name.contains(q, autoescape=True),
            Datum.value.contains(q, autoescape=True)
        )).all()
        cds = ChildDatum.query.filter(ChildDatum.name.contains(q, autoescape=True)).all()
        data += list(map(lambda cd: cd.parent, cds))
        data = list(filter(check_obj_uniqueness, data))

        results['data'] = list(map(lambda datum: datum.to_obj(whos_asking=auth_user), data))

    return results
