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


MAJOR_REGIONS_TABLE = '//home/maps/core/nmaps/analytics/geo-data/major_regions_map'


def make_user_edit_data(job, date, major_regions):
    '''
    Main work of statistics
    1. Prepare raw tables: nmaps_moderation_tasks, nmaps_user_raw
    2. Add tree for event_type and object_type
    3. Add users role (moderator, yandex-moderator, cartographer)
    4. Add region_tree
    5. Aggregate table and count sum of tasks
    '''
    nmaps_moderation_tasks = stream_processors.make_moderation_tasks(job, date)

    nmaps_user_raw = stream_processors.make_nmaps_user_raw(job, date)

    nmaps_moderation_with_path = stream_processors.add_paths(
        job,
        nmaps_moderation_tasks,
        nmaps_user_raw
    )

    stream = stream_processors.set_region_tree(
        nmaps_moderation_with_path,
        major_regions
    ).label('add_region_tree')

    return stream_processors.prepare_result_counts(
        stream
    ).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):

    major_regions = job.table(
        MAJOR_REGIONS_TABLE
    ).label('major_regions')

    report_data = make_user_edit_data(job, date, major_regions)

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