import getpass
import geobase6
import os
import tempfile
import qb2.api.v1.resources as qr
import nile.api.v1.files as nf


GEOBASE_JOB_MEMORY_LIMIT_MB = 8 * 1024

GEODATA_RESOURCE = 'geodata6.bin'
GEODATA_YT_STATBOX = '//statbox/statbox-dict-last/geodata5.bin'

LOOKUP = None
FILES = [nf.RemoteFile(GEODATA_YT_STATBOX)]


def init_geodata_from_resource():
    global LOOKUP
    global FILES
    if not LOOKUP:
        LOOKUP = geobase6.Lookup(GEODATA_RESOURCE)
        FILES = []


def init_geodata_from_yt_copy(yt_client):
    global LOOKUP
    if not LOOKUP:
        geodata_path = os.path.abspath(os.path.join(tempfile.gettempdir(), getpass.getuser() + '-' + GEODATA_RESOURCE))

        with open(geodata_path, "wb") as dest_file:
            for chunk in yt_client.read_file(GEODATA_YT_STATBOX).chunk_iter():
                dest_file.write(chunk)

        LOOKUP = geobase6.Lookup(geodata_path)


def _init_geodata():
    global LOOKUP
    # resource 'ArcGeobase' uses file 'geodata5.bin'
    # as described in resource description:
    # https://a.yandex-team.ru/arc/trunk/arcadia/statbox/qb2/qb2_extensions/resources/location.py?rev=7135091#L248
    LOOKUP = qr.get('ArcGeobase')


def lookup():
    global LOOKUP
    if not LOOKUP:
        _init_geodata()
    return LOOKUP
