from yandex.maps import geolib3
from sprav.protos.export_pb2 import TExportedCompany

from nile.api.v1 import (
    extractors as ne,
    stream as ns,
    Job
)

import typing as tp

NYAK_MAPPING_PATH: str = '//home/altay/db/export/current-state/snapshot/nyak_mapping'


def point_ewkb_from_proto(proto: str) -> tp.Optional[str]:
    company = TExportedCompany()
    company.ParseFromString(proto)
    if not company.HasField('Geo'):
        return None
    return geolib3.Point2(
        company.Geo.Location.Pos.Lon,
        company.Geo.Location.Pos.Lat) \
        .to_EWKB(geolib3.SpatialReference.Epsg4326).hex()


def closed_from_proto(proto: str) -> bool:
    company = TExportedCompany()
    company.ParseFromString(proto)
    is_closed = company.HasField('ClosedKind') and \
        company.ClosedKind == TExportedCompany.EClosedKind.Permanent
    is_reliable = not company.HasField('Unreliable') or not company.Unreliable
    return is_closed and is_reliable


def altay_data_table(job: Job) -> ns.Stream:
    return job.table(NYAK_MAPPING_PATH).project(
        ft_id=ne.custom(
            lambda id: int(id), 'original_id'
        ).with_type(int),
        permalink_id=ne.custom(
            lambda id: str(id), 'permalink'
        ).with_type(str),
        geom_altay=ne.custom(
            lambda proto: point_ewkb_from_proto(proto), 'export_proto'
        ).with_type(str),
        is_closed=ne.custom(
            lambda proto: closed_from_proto(proto), 'export_proto'
        ).with_type(bool)
    )
