import configparser
import json
import os

# read config file based on already set environment variable : APP_ENV
# If  APP_ENV is null default configuration file is used
#  New application config file should be in folder with same name as environment variavble
APP_ENV = os.environ.get('APP_ENV')
if not APP_ENV:
    APP_ENV = 'app'

config = configparser.ConfigParser()
CONFIGURATION_FILE = f"conf/{APP_ENV}/application.conf"
config.read(CONFIGURATION_FILE)
if not config.read(CONFIGURATION_FILE):
    APP_ENV = "dev"
    CONFIGURATION_FILE = f"conf/{APP_ENV}/application.conf"
    config.read(CONFIGURATION_FILE)




"""
Configuration module
"""

"""
Service Info
"""

SERVICE_NAME = config["service"]["name"]
SERVICE_HOST = config["service"]["host"]
SERVICE_PORT = config.getint("service", "port")
SERVICE_SECRET_KEY = config["service"]["SECRET_KEY"]
SERVICE_ENABLE_SECURITY = config.getboolean("service", "enable_security", fallback=False)
SERVICE_INTERFACE = str(config["service"]["interface"])
DEVICE_STATUS_TIME = config.getint("service", "device_status_time_minutes", fallback=1)
APPLY_PROCESSOR_COUNT = config.getboolean("service", "apply_processor_count", fallback=False)
workers = config.getint("service", "workers", fallback=1)
threads = config.getint("service", "threads", fallback=1)
ip_check = config.getboolean("service", "ip_check", fallback=False)


cookie_max_age = config.getint("service", "cookie_max_age_in_mins", fallback=60)
max_attempts = config.getint("service", "max_attempts")
lockout_time_interval = config.getint("service", "lockout_time_interval")
reset_time_interval = config.getfloat("service", "reset_time_interval")

http_flag = config.getboolean('service', 'httpflag')
secure_flag = config.getboolean('service', 'secureflag')

"""
Log Info
"""
LOG_FILE_NAME = config["log"]["file_name"]
LOG_PATH = config["log"]["path"]
LOG_LEVEL = config["log"]["level"]
LOG_HANDLER = config["log"]["handler"]
LOG_MAX_BYTES = config.getint("log", "max_bytes")
LOG_BACKUP_COUNT = config.getint("log", "back_up_count")

"""
Mongo Info
"""
MONGO_HOST = config["mongo_db"]["host"]
MONGO_PORT = config.getint("mongo_db", "port", fallback=2717)
MONGO_USERNAME = config["mongo_db"]["username"]
MONGO_PASSWORD = config["mongo_db"]["password"]
MONGO_AUTHSOURCE = config["mongo_db"]["authSource"]
MONGO_AUTHMECHANISM = config["mongo_db"]["authMechanism"]
encryption_constants_file_path = config["mongo_db"]["mongo_constants_file_path"]

"""
Kairos Info
"""
KAIROS_DB_URL = config["kairos_db"]["url"]

"""
Additional info
"""
SYSTEM_LOGIN_DOMAIN_DOMAIN_LIST = json.loads(config["system_login"]["domain_list"])
CSV_PATH = config["csv_conf"]["csv_path"]
UPLOAD_CSV_PATH = config["csv_conf"]["upload_path"]
PROFILE_PIC_PATH = config["profile_pic_path"]["base_path"]

"""
Manual Entry conf
"""
SCHEDULER_BASE_URL = config["schedule_rule_engine"]["url"]

"""
Upload Parser
"""
# upload_parser = config["upload_parser"]

"""
Default email sender
"""
default_email_url = config["email_default_baseurl"]["base_url"]

"""
AI Rule : Auto Container Deployment Service
"""
AI_RULE_STATUS = config["ai_rules"]["enabled"]
if AI_RULE_STATUS.lower() == "true":
    AI_RULE_DOCKER_ENDPOINT = config["ai_rules"]["docker_endpoint"]
else:
    AI_RULE_DOCKER_ENDPOINT = "localhost"

CONTAINER_URL = config["flow_model"]["container_url"]

IMAGE_PATH = config.get('IMAGE', 'path', fallback="images/")

LICENSE_PATH = config.get('LICENSE_PATH', 'path', fallback="license/")

PIPELINE_INTERNAL_SECTION = 'pipeline_internal'
PIPELINE_INTERNAL_CONFIGURATION = {
    "mqtt_broker_host": config.get(PIPELINE_INTERNAL_SECTION, 'mqtt_broker_host', fallback='localhost'),
    "mqtt_broker_port": config.get(PIPELINE_INTERNAL_SECTION, 'mqtt_broker_port', fallback='1883'),
    "mqtt_broker_ssl": config.get(PIPELINE_INTERNAL_SECTION, 'mqtt_broker_ssl', fallback='false'),
    "mqtt_broker_conn_type": config.get(PIPELINE_INTERNAL_SECTION, 'mqtt_broker_conn_type', fallback='tcp'),
    "mqtt_broker_ws_port": config.get(PIPELINE_INTERNAL_SECTION, 'mqtt_broker_ws_port', fallback='8083'),
    "kafka_broker": config.get(PIPELINE_INTERNAL_SECTION, 'queue_host', fallback='localhost'),
    "kafka_port": config.get(PIPELINE_INTERNAL_SECTION, 'queue_port', fallback='localhost'),
    "broker_ssl_path": config.get(PIPELINE_INTERNAL_SECTION, 'broker_ssl_path', fallback='/opt/ssl'),
    "node_intermediate": 'kafka' if config.get(PIPELINE_INTERNAL_SECTION, 'node_intermediate',
                                               fallback='kafka') == 'queue' else "mqtt"
}
CHANNEL_PIPELINE_CONFIG = config['channel_pp_debug_node']

MQTT_BROKER_HOST = config['pipeline_internal']["mqtt_broker_host"]
MQTT_BROKER_PORT = config['pipeline_internal']["mqtt_broker_port"]
MQTT_BROKER_SSL = config['pipeline_internal']["mqtt_broker_ssl"]
MQTT_BROKER_CONN_TYPE = config['pipeline_internal']["mqtt_broker_conn_type"]
MQTT_BROKER_WS_PORT = config['pipeline_internal']["mqtt_broker_ws_port"]
BROKER_SSL_PATH = PIPELINE_INTERNAL_CONFIGURATION.get("broker_ssl_path", '/opt/ssl')

MANAGER_URL = config["AGENT"]["manager_url"]
DEVICE_MODE = config.get('AGENT', 'device_mode', fallback='agent')
SSL_CERT_PATH = config.get('AGENT', 'ssl_base_path', fallback='/opt/ssl')
TIME_SYNC_URL = config.get('AGENT', 'time_sync_url', fallback=None)
TIME_SYNC_URL_CERT_PATH = config.get('AGENT', 'cert_path', fallback=False)

#  Redis Details
redis_host = str(config["REDIS"]["host"])
redis_port = int(config["REDIS"]["port"])
key_expiry_in_secs = int(config["REDIS"]["key_expiry"])
rules_redis_db = int(config["REDIS"]["rules_db"])
alarms_redis_db = int(config["REDIS"]["alarms_db"])
live_tags_db = int(config["REDIS"]["live_tags_db"])
audit_db = int(config["REDIS"]["audit_db"])
audit_queue = str(config["REDIS"]["audit_queue"])

#iLens version
version = str(config["ILENS_VERSION"]["version"])

# Data Processor configs
data_processor_host = config.get('DATA_PROCESSOR', 'host', fallback=None)
data_processor_conn_type = config.get('DATA_PROCESSOR', 'connection', fallback='tcp')
data_processor_ssl = bool(config.get('DATA_PROCESSOR', 'ssl_enabled', fallback=False))
data_processor_port = int(config.get('DATA_PROCESSOR', 'port', fallback=1883))
data_processor_topic = str(config.get('DATA_PROCESSOR', 'topic', fallback=None))

LICENSE_SERVER = config.get('LICENSE_SERVER','host', fallback="localhost")
LICENSE_PORT = config.get('LICENSE_SERVER','port', fallback=9816)