from nile.api.v1 import (
    filters as nf,
    aggregators as na,
    extractors as ne,
    datetime as nd,
    statface as ns,
    cli
)

import datetime

LOG_PATH = '//home/logfeller/logs/nmaps-feedback-log/1d/'
REPORT_PATH = 'Maps.Wiki/Feedback/Autogen.Hypotheses'
SCALE = 'd'
SOURCES = [
    'gps',
    'mrc',
    'hypotheses-rips',
    'route-lost',
]

source_to_report_measure = lambda s: s.replace('-', '_')


def make_job(job, nirvana, options, statface_client):

    dates = str(datetime.date.today() - datetime.timedelta(days=1)) if options.yesterday else options.dates

    job = job.env(
        templates=dict(
            dates=dates
        )
    )

    log = job.table(LOG_PATH + "@dates")
    report = ns.StatfaceReport() \
        .path(REPORT_PATH)\
        .scale(SCALE)\
        .client(statface_client)

    aggregates = dict([
        (
            source_to_report_measure(source),
            na.count(predicate=nf.equals('source', source))
        )
        for source in SOURCES
    ])

    log = log.filter(
        nf.and_(
            nf.equals('action', 'created'),
            nf.equals('workflow', 'task'),
            nf.custom(lambda source: source in SOURCES, 'source'),
            nf.custom(lambda type: not type.endswith('-sign'), 'type')
        )
    ).project(
        ne.all(),
        fielddate=ne.custom(lambda iso: str(nd.Datetime.from_iso(iso).date()), 'iso_eventtime')
    ).groupby(
        'fielddate'
    ).aggregate(
        **aggregates
    ).publish(report, allow_change_job=True)

    return job


if __name__ == "__main__":

    make_job = cli.statinfra_job(
        options=[
            cli.Option('yesterday', default=True),
        ]
    )(make_job)

    cli.run()
