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_CRT_data(job, date, major_regions):
    '''
    Main work of statistics
    1. Prepare raw tables: edits_count_per_user, nmaps_edits_raw, nmaps_user_raw
    2. Add tree for action, status and object
    3. Prepare table for counts
    4. Add region_tree
    5. Aggregate table and count summ of users, commits and edits
    '''
    bebr_filter_table_raw = stream_processors.make_bebr_table_with_filter(job, date)

    edits_count_per_user = stream_processors.make_edits_count_per_user(job, date)

    nmaps_edits = stream_processors.make_nmaps_edits(job, date)

    nmaps_user_raw = stream_processors.make_nmaps_user_raw(job, date)

    nmaps_users_status = stream_processors.add_user_path(
        job,
        edits_count_per_user,
        nmaps_user_raw
    )

    bebr_filter_table = stream_processors.add_event_path(
        job,
        bebr_filter_table_raw
    )

    bebr_table_with_count_edits = stream_processors.make_nmaps_edits_for_count(
        job,
        nmaps_edits,
        bebr_filter_table,
        nmaps_users_status
    )

    bebr_table_with_region_tree = stream_processors.set_region_tree(
        bebr_table_with_count_edits,
        major_regions
    ).label('add_region_tree')

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

    report_data.publish(
        report,
        allow_change_job=True
    )

    return job


def make_job(job, scale, statface_client, date, report_name, result_path):

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

    report_data = make_CRT_data(job, date, major_regions)

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