from .schema import TASKS_LOG_SCHEMA
from maps.wikimap.stat.libs.feedback import get_task_id, PAID_OPERATIONS
from maps.wikimap.stat.libs.geobase_regions import (
    FILES as GEOBASE_FILES,
    GEOBASE_JOB_MEMORY_LIMIT_MB,
    lon_lat_position_to_region_id,
)
from nile.api.v1 import (
    utils as nu,
    Record,
)
import qb2.api.v1.filters as qf


def get_feedback_tasks(feedback_task_table, min_action_date):
    '''
    feedback_task_table:
    | id  | position | source | type | resolved_at | history | ... |
    |-----+----------+--------+------+-------------+---------+-----|
    | ... | ...      | ...    | ...  | ...         | ...     | ... |

    result:
    | entity_id | entity_domain | action_by          | action_at          | action            | task_id | region_id           |
    |-----------+---------------+--------------------+--------------------+-------------------+---------+---------------------|
    | id        | "feedback"    | history.modifiedBy | history.modifiedAt | history.operation | ...     | region_id(position) |
    '''
    @nu.with_hints(output_schema=TASKS_LOG_SCHEMA)
    def history_to_paid_operations(records):
        for record in records:
            for event in record.history:
                if event[b'operation'] in PAID_OPERATIONS and event[b'modifiedAt'].decode() > min_action_date:
                    yield Record(
                        entity_id=str(record['id']),
                        entity_domain='feedback',
                        action_by=event[b'modifiedBy'],
                        action_at=event[b'modifiedAt'].decode(),
                        action=event[b'operation'].decode(),
                        task_id=get_task_id(record['source'], record['type'], event[b'operation']).decode(),
                        region_id=lon_lat_position_to_region_id(record['position']),
                    )

    return feedback_task_table.filter(
        qf.compare('resolved_at', '>=', min_action_date, default=True),
    ).map(
        history_to_paid_operations,
        memory_limit=GEOBASE_JOB_MEMORY_LIMIT_MB,
        files=GEOBASE_FILES,
    )
