#!/usr/bin/python
# -*- coding: utf-8 -*-

#import importlib.resources

import os
from rivista.config import Cache, Data, Settings
from rivista.utilities import Toml
from rivista.http.instance import HttpInstance
import shutil
import uvicorn

def main():
    http_instance = HttpInstance()
    return http_instance.app

if __name__ == 'rivista.__main__':

    directory = os.path.dirname(__file__)

    # Copy data files
    # FIXME File settins.toml is copied too.
    directory_data = Data.get_directory()
    if not os.path.exists(directory_data):
        directory_assets = os.path.join(directory, 'assets')
        directory_assets_new = shutil.copytree(directory_assets, directory_data)
        print(f'Data directory {directory_assets_new} has been created and populated.')

    # Copy settings files
    directory_settings = Settings.get_directory()
    if not os.path.exists(directory_settings):
        directory_configs = os.path.join(directory, 'configs')
        directory_settings_new = shutil.copytree(directory_configs, directory_settings)
        print(f'Settings directory {directory_settings_new} has been created and populated.')

    # Create cache directories
    directory_cache = Cache.get_directory()
    if not os.path.exists(directory_cache):
        print(f'Creating a cache directory at {directory_cache}.')
        os.mkdir(directory_cache)
    # TODO Add more cache directories (see JabberCard).
    # TODO Remove json (indices is the new name)
    for subdirectory in ('json', 'indices', 'pubsub'):
        subdirectory_cache = os.path.join(directory_cache, subdirectory)
        if not os.path.exists(subdirectory_cache):
            print(f'Creating a cache subdirectory at {subdirectory_cache}.')
            os.mkdir(subdirectory_cache)

    # Configure settings file
    file_settings = os.path.join(directory_settings, 'settings.toml')
    if not os.path.exists(file_settings):
        directory_configs = os.path.join(directory, 'configs')
        file_settings_empty = os.path.join(directory_configs, 'settings.toml')
        shutil.copyfile(file_settings_empty, file_settings)
    data_settings = Toml.open_file_toml(file_settings)

    # Configure account
    data_settings_account = data_settings['account']

    settings_account = {
        'xmpp': 'Set a Jabber ID',
        'pass': 'Input Password'
    }

    for key in settings_account:
        data_settings_account_value = data_settings_account[key]
        if not data_settings_account_value:
            settings_account_message = settings_account[key]
            while not data_settings_account_value:
                data_settings_account_value = input(f'{settings_account_message}: ')
            data_settings_account[key] = data_settings_account_value

    # Configure default PubSub Service and Node Name
    data_settings_default = data_settings['default']
    
    settings_default_default = {
        'pubsub': 'pubsub.woodpeckersnest.space',
        'nodeid': 'PlanetJabber'
    }

    for key in settings_default_default:
        data_settings_default_value = data_settings_default[key]
        if not data_settings_default_value:
            settings_default_default_value = settings_default_default[key]
            data_settings_default_value = input(f'Set brand {key} (default: "{settings_default_default_value}"): ')
            if not data_settings_default_value: data_settings_default_value = settings_default_default_value
        data_settings_default[key] = data_settings_default_value

    # Configure Settings
    data_settings_settings = data_settings['settings']

    data_settings_settings_service = data_settings_settings['service']
    if data_settings_settings_service is '':
        while data_settings_settings_service not in ('n', 'N', 'no', 'No', 'y', 'Y', 'yes', 'Yes'):
            data_settings_settings_service = input(f'Run as service? [Y/n] ')
        if data_settings_settings_service in ('y', 'Y', 'yes', 'Yes'):
            data_settings_settings['service'] = 1
        else:
            data_settings_settings['service'] = 0

    data_settings_settings_include = data_settings_settings['include']
    if data_settings_settings_include is '':
        data_settings_settings_include = input(f'Limit service to included domains? (comma separated. remain empty for no limit) ')
        data_settings_settings['include'] = data_settings_settings_include if data_settings_settings_include else 0

    data_settings_settings_operator = data_settings_settings['operator']
    if data_settings_settings_operator is '':
        data_settings_settings['operator'] = input(f'Set a Jabber ID of an operator to contact with: ')

    Toml.save_to_toml(file_settings, data_settings)

    # Start JabberCard
    app = main()
    uvicorn.run(app, host='localhost', port=8000, reload=False)
