# -*- coding: utf-8 -*-
from datacloud.score_api.storage.users.generic import User, UserStorage
from datacloud.score_api.storage.ydb.ydb_tables.config_tables.partner_tokens_table import PartnerTokensTable

from datacloud.score_api.storage.cache.ttl_cache import TtlCache

__all__ = [
    'YdbUserStorage'
]


class YdbUserStorage(UserStorage):
    """
    User storage that stores info in YandexDataBase
    """
    def __init__(self, ydb_manager, database, table_path):
        super(YdbUserStorage, self).__init__()
        self._ydb_manager = ydb_manager
        self._database = database
        self._table_path = table_path

        self._cache = TtlCache(300)

    def get_user_by_token(self, token, address=None):
        status, val = self._cache.get(token)
        if status == TtlCache.Status.OK:
            return User(id=val)

        user_rec = PartnerTokensTable(self._ydb_manager, self._database, self._table_path).get_one(token)
        if not user_rec:
            return None

        self._cache.insert(token, user_rec.partner_id)

        return User(id=user_rec.partner_id)
