import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

server_secrets_DIR = os.path.join(BASE_DIR, 'server_secrets')

SKB = os.path.join(server_secrets_DIR, 'SECRET_KEY.bin')
DBG = os.path.join(server_secrets_DIR, 'DEBUG.txt')
STD = os.path.join(server_secrets_DIR, 'SITE.tld')
STN = os.path.join(server_secrets_DIR, 'SITE.txt')
XTRACFG = os.path.join(server_secrets_DIR, 'extraconfig.py')
RGO = os.path.join(server_secrets_DIR, 'REGISTRATION_OPEN.txt')
LNGS = os.path.join(BASE_DIR, 'webproj', 'locale')
LNGSo = os.path.join(server_secrets_DIR, 'active_languages.html')
TGT = os.path.join(server_secrets_DIR, 'telegram.token')
TGNM = os.path.join(server_secrets_DIR, 'telegram.name')

if not os.path.exists(server_secrets_DIR):
    os.makedirs(server_secrets_DIR)

if not os.path.exists(LNGS):
    os.makedirs(LNGS)

if not os.path.exists(SKB):
    with open(SKB, 'wb') as f:
        f.write(os.urandom(512))

if not os.path.exists(XTRACFG):
    with open(XTRACFG, 'wt') as f:
        f.write('\n')

if not os.path.exists(DBG):
    with open(DBG, 'wt') as f:
        f.write('False')

if not os.path.exists(RGO):
    with open(RGO, 'wt') as f:
        f.write('True')

if not os.path.exists(STD):
    with open(STD, 'wt') as f:
        f.write('bot.furmeet.app\n.furmeet.app')

if not os.path.exists(STN):
    with open(STN, 'wt') as f:
        f.write('FurmeetApp\'s Group Chat Bot')

if not os.path.exists(TGT):
    with open(TGT, 'wt') as f:
        f.write('')

if not os.path.exists(TGNM):
    with open(TGNM, 'wt') as f:
        f.write('')


def isTrue(s: str) -> bool:
    return s in ['1', 'true', 't', 'True', 'TRUE', 'yes', 'y', 'YES', 'Yes']


SECRET_KEY = None
DEBUG = None
SITE_DOMAIN = None
REGISTRATION_OPEN = None
SITE_NAME = None
LANGUAGES = list()
TELEGRAM_TOKEN = None
TELEGRAM_NAME = None

with open(SKB, 'rb') as f:
    SECRET_KEY = f.read()

with open(DBG, 'rt') as f:
    DEBUG = isTrue(f.read().strip())

with open(RGO, 'rt') as f:
    REGISTRATION_OPEN = isTrue(f.read().strip())

with open(STD, 'rt') as f:
    SITE_DOMAIN = list(map(str.strip, f.read().strip().splitlines()))

with open(STN, 'rt') as f:
    SITE_NAME = f.read().strip()

with open(TGT, 'rt') as f:
    TELEGRAM_TOKEN = f.read().strip()

with open(TGNM, 'rt') as f:
    TELEGRAM_NAME = f.read().strip()

for language_code in sorted(os.listdir(LNGS)):
    lc = language_code.lower().replace(' ', '-').replace('_', '-')
    LANGUAGES.append((
        lc,
        'lang__'+lc
    ))

with open(LNGSo, 'wt') as f:
    f.write('{# Autogenerated document for the sole purpose of triggering ')
    f.write('addition of translation entry in internationalization framework #}\n')
    f.write('<ol>\n\t')
    f.write('\n\t'.join([
        '<li id="%s">{%% trans \'%s\' %%}</li>' % (
            lang_code,
            lang_trans.replace('\\', '\\\\').replace('\'', '\\\''),
        )
        for lang_code, lang_trans in LANGUAGES
    ]))
    f.write('\n</ol>\n')
