import os
import logging
from logging.handlers import RotatingFileHandler

import redis
from redis.sentinel import Sentinel

WSGI_PROC_NUM = 4
TASK_LIFESPAN = 60 * 60 * 24 * 7

ENV_TYPE = os.environ.get('ENV_TYPE', 'local')

if ENV_TYPE == 'production':
    TANK_FINDER_HOST = 'tank-finder.yandex-team.ru'
    VALIDATOR_HOST = 'tank-validator.yandex-team.ru'
else:
    TANK_FINDER_HOST = 'tank-finder-test.in.yandex-team.ru'
    VALIDATOR_HOST = 'tank-validator.test.in.yandex-team.ru'


class Config:
    SECRET_KEY = os.environ.get('FIRESTARTER_SECRET_KEY', '')

    db_config = {
        'host': os.environ.get('FIRESTARTER_HOST', 'sas-xxcxaae0scdjvc5y.db.yandex.net'),
        'port': os.environ.get('FIRESTARTER_PORT', 6379),
        'name': os.environ.get('FIRESTARTER_DB_NAME', 8),
        'pass': os.environ.get('FIRESTARTER_REDIS_PWD', '')
    }


def setup_logger():
    logger = logging.getLogger(__name__)
    logger.setLevel(logging.DEBUG)

    log_filename = 'firestarter.log' if ENV_TYPE == 'local' else '/var/log/firestarter/firestarter.log'
    ch = logging.StreamHandler()
    fh = RotatingFileHandler(filename=log_filename, maxBytes=1024*1024*50, backupCount=10)
    formatter = logging.Formatter('%(asctime)s - thread %(thread)d - %(filename)s:%(lineno)d - %(levelname)s %(message)s')
    ch.setFormatter(formatter)
    fh.setFormatter(formatter)
    logger.addHandler(ch)
    logger.addHandler(fh)

    return logger


def init_db(db_config=None):
    if not db_config:
        db_config = Config.db_config

    if ENV_TYPE == 'production':
        firestarter_host_node1 = os.environ.get('FIRESTARTER_HOST_NODE1', 'sas-miiunh1mk0y7agyt.db.yandex.net')
        firestarter_host_node2 = os.environ.get('FIRESTARTER_HOST_NODE2', 'vla-mz7hiuemezk0a5xg.db.yandex.net')
        firestarter_sentinel_port = os.environ.get('FIRESTARTER_SENTINEL_PORT', 26379)
        sentinel = Sentinel(
            [(h, firestarter_sentinel_port) for h in [firestarter_host_node1, firestarter_host_node2]],
            socket_timeout=0.1, db=os.environ.get('FIRESTARTER_DB_NAME', 8)
        )
        master = sentinel.master_for('firestarter_redis_production', password=db_config['pass'])
        slave = sentinel.slave_for('firestarter_redis_production', password=db_config['pass'])
    elif ENV_TYPE == 'local':
        db = redis.StrictRedis(
            host='localhost',
            port=6379,
            db=5
        )
        master, slave = db, db
    else:
        db = redis.StrictRedis(
            host=db_config['host'],
            port=db_config['port'],
            db=db_config['name'],
            password=db_config['pass']
        )
        master, slave = db, db

    return master, slave


logger = setup_logger()
redis_master, redis_slave = init_db(Config.db_config)
