from . import stream_processors
from nile.api.v1 import (
    statface as ns
)


def make_user_edit_data(job, date):
    '''
    Main work of statistics
    1. Prepare raw tables: nmaps_acl_roles, nmaps_user_raw
    2. Add tree for role
    3. Aggregate table and count sum of puid
    '''
    nmaps_acl_roles = stream_processors.make_acl_roles(job, date)

    nmaps_user_raw = stream_processors.make_nmaps_user_raw(job, date)

    nmaps_acl_roles_with_path = stream_processors.add_paths(
        job,
        nmaps_acl_roles,
        nmaps_user_raw
    )

    return stream_processors.prepare_result_counts(
        nmaps_acl_roles_with_path
    ).label('prepare_result_counts')


def publish_data(report_data, report_name, scale, statface_client, job, date):
    '''
    Publish results in Statface
    '''
    report = ns.StatfaceReport() \
        .path(report_name) \
        .scale(scale) \
        .client(statface_client) \
        .default_max_distance(1)

    report_data.publish(
        report,
        allow_change_job=True
    )

    return job


def make_job(job, scale, statface_client, date, report_name, result_path=None):
    report_data = make_user_edit_data(job, date)

    job = publish_data(
        report_data,
        report_name,
        scale,
        statface_client,
        job,
        date
    )
    return job
