import os
import logging
from logging.handlers import RotatingFileHandler

from library.python.vault_client.instances import Production as VaultClient
from library.python.vault_client.errors import ClientError

redis_secret = os.environ.get("CACHE_REDIS_PASSWORD")
env_type = os.environ.get("ENV_TYPE") or 'testing'
yp_token = os.environ.get("YP_TOKEN")
cache_type = os.environ.get("CACHE_TYPE") or 'redis'
cache_redis_host = os.environ.get("CACHE_REDIS_HOST") or 'sas-xxcxaae0scdjvc5y.db.yandex.net'
cache_redis_port = os.environ.get("CACHE_REDIS_PORT") or 6379
cache_default_timeout = os.environ.get("CACHE_DEFAULT_TIMEOUT") or 300
cache_redis_sentinels_host_1 = os.environ.get("CACHE_REDIS_SENTINELS_HOST_1")
cache_redis_sentinels_port = os.environ.get("CACHE_REDIS_SENTINELS_PORT")
cache_redis_sentinels_host_2 = os.environ.get("CACHE_REDIS_SENTINELS_HOST_2")
cache_redis_sentinels_master = os.environ.get("CACHE_REDIS_SENTINEL_MASTER")

if not (redis_secret or yp_token):
    try:
        yav_client = VaultClient(decode_files=True)
        if not redis_secret:
            redis_secret = yav_client.get_version("sec-01dvartpx21sphjafnws1rwgvt")["value"]["REDIS_PWD"]
        if not yp_token:
            yp_token = yav_client.get_version("sec-01d29tnxhn45y1vytr190qzy41")["value"]["yp-token"]
    except ClientError as e:
        logging.error('Can\'t get yp token: %s', e)


def setup_logger():
    logger = logging.getLogger(__name__)
    logger.setLevel(logging.DEBUG)
    handler = RotatingFileHandler(filename=u'tank-finder.log', maxBytes=1024*1024*100, backupCount=10)
    formatter = logging.Formatter(u'%(levelname)-8s [%(asctime)s] %(message)s')
    handler.setFormatter(formatter)
    logger.addHandler(handler)

    return logger


class Config(object):
    PUBLIC_TANKS_RTC_URL = 'https://nanny.yandex-team.ru/v2/services/{}/current_state/instances/'
    PUBLIC_TANKS_CONDUCTOR_URL = 'https://c.yandex-team.ru/api-cached/generator/get_dc_from_group?group=tanks_common'
    RACKTABLES_URL = 'https://ro.racktables.yandex-team.ru/export/networklist.php?report=all-metadc&json'
    TANKS_CACHE_INFO_LIFETIME = 86400


class TestingtConfig(Config):
    REDIS_CACHE = {
        "CACHE_TYPE": cache_type,
        "CACHE_REDIS_HOST": cache_redis_host,
        "CACHE_REDIS_PORT": cache_redis_port,
        "CACHE_REDIS_PASSWORD": redis_secret,
        "CACHE_DEFAULT_TIMEOUT": cache_default_timeout
    }


class ProductionConfig(Config):
    REDIS_CACHE = {
        "CACHE_TYPE": cache_type,
        "CACHE_REDIS_SENTINELS": [(cache_redis_sentinels_host_1, cache_redis_sentinels_port), (cache_redis_sentinels_host_2, cache_redis_sentinels_port)],
        "CACHE_REDIS_SENTINEL_MASTER": cache_redis_sentinels_master,
        "CACHE_REDIS_PORT": cache_redis_sentinels_port,
        "CACHE_REDIS_PASSWORD": redis_secret,
        "CACHE_DEFAULT_TIMEOUT": cache_default_timeout
    }


logger = setup_logger()
