from maps.wikimap.stat.libs.feedback import get_task_id
from maps.wikimap.stat.libs.geobase_regions import (
    FILES as GEOBASE_FILES,
    GEOBASE_JOB_MEMORY_LIMIT_MB,
    lon_lat_position_to_region_id,
)
import nile.api.v1.extractors as ne
from qb2.api.v1 import (
    filters as qf,
    typing,
)


def get_feedback_tasks(feedback_task_table, min_created_date):
    '''
    feedback_task_table:
    | id  | position | source | type | created_at | ... |
    |-----+----------+--------+------+------------+-----|
    | ... | ...      | ...    | ...  | ...        | ... |

    result:
    | entity_id | position | source | type |
    |-----------+----------+--------+------|
    | id        | ...      | ...    | ...  |
    '''
    return feedback_task_table.filter(
        qf.compare('created_at', '>=', min_created_date),
    ).project(
        entity_id=ne.custom(int, 'id').with_type(typing.Int64),
        position='position',
        source='source',
        type='type',
    )


def add_task_id_region_id(graded_units, feedback_tasks):
    '''
    graded_units:
    | entity_id | <columns> |
    |-----------+-----------|
    | event_id  | ...       |

    feedback_tasks:
    | entity_id | position | source | type |
    |-----------+----------+--------+------|
    | ...       | ...      | ...    | ...  |

    result:
    | entity_id | region_id                            | task_id | <columns> |
    |-----------+--------------------------------------+---------+-----------|
    | id        | lon_lat_position_region_id(position) | ...     | ...       |
    '''
    return graded_units.filter(
        qf.equals('entity_domain', 'feedback')
    ).project(
        ne.all(exclude='entity_id'),
        entity_id=ne.custom(int, 'entity_id').with_type(typing.Int64),
    ).join(
        feedback_tasks,
        by='entity_id',
        type='inner',
        assume_small_left=True,
        assume_unique_left=True,
        assume_unique_right=True,
    ).project(
        ne.all(exclude=('position', 'source', 'type', 'entity_id')),
        region_id=ne.custom(lon_lat_position_to_region_id, 'position').with_type(typing.Int64),
        task_id=ne.custom(
            lambda src, tp, action: get_task_id(src, tp, action.encode()).decode(),
            'source',
            'type',
            'action',
        ).with_type(typing.Unicode),
        entity_id=ne.custom(str, 'entity_id').with_type(typing.Unicode),
        memory_limit=GEOBASE_JOB_MEMORY_LIMIT_MB,
        files=GEOBASE_FILES,
    )
