#!/usr/bin/env python
'''
Create or modify the tios configuration file interactively.
'''
from tios import environments
import getpass
import argparse
try:
    import popylar
    has_popylar = True
except ImportError:
    has_popylar = False
import sys

if sys.version_info[0] == 2:
    input = raw_input

parser = argparse.ArgumentParser(description='Create or modify the *tios* configuration file')
args = parser.parse_args()

tios_env = environments.load_mongo_env(authenticate=False)

for key in ['DB_URL', 'DB_NAME', 'DB_COLLECTION', 'DB_USER', 'DB_PWD']:
    if not key in tios_env:
        tios_env[key] = ''

if not 'IMD_PORT' is tios_env:
    tios_env['IMD_PORT'] = 40237

if not 'DB_PORT' is tios_env:
    tios_env['DB_PORT'] = 27017

response = input("Database URL ({}):".format(tios_env['DB_URL']))
if response != "":
    tios_env['DB_URL'] = response

response = input("Database Port ({}):".format(tios_env['DB_PORT']))
if response != "":
    tios_env['DB_PORT'] = response

response = input("IMD Port ({}):".format(tios_env['IMD_PORT']))
if response != "":
    tios_env['IMD_PORT'] = response

response = input("Database name ({}):".format(tios_env['DB_NAME']))
if response != "":
    tios_env['DB_NAME'] = response

response = input("Username ({}):".format(tios_env['DB_USER']))
if response != "":
    tios_env['DB_USER'] = response
    tios_env['DB_COLLECTION'] = response

response = getpass.getpass("Password (hit return to leave unchanged):")
if response != "":
    tios_env['DB_PWD'] = response

tios_env = environments.load_mongo_env(source=tios_env, authenticate=True)
environments.save_mongo_env(tios_env)

response = input("Allow collection of anonymised usage data (Y/N):").upper()
if len(response) > 0 and response[0] == "Y":
    if has_popylar:
        popylar.opt_in()
    else:
        print('Thank you: please install the \"popylar\" python package and re-run \nthis command to activate usage data collection')
else:
    if has_popylar:
        popylar.opt_out()

