#! /usr/bin/env python

# Copyright 2017 NEWCRAFT GROUP B.V.
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.

import io
import logging
import logging.config
import os
import sys

from confload import Config

from commandable import CommandLoader

sys.path.append(os.getcwd())

logger = logging.getLogger(__name__)


def create_config():
    if os.path.isfile('config.yml'):
        return

    print("\nEnter the relative path(s) to the commands directory (emtpy to exit):")

    f = io.open("config.yml", "wt", encoding="utf-8")
    f.write("Commands:\n")
    f.close()


class App:

    def __init__(self, cli: bool):
        self.cli = cli
        if os.path.isfile('logger.ini'):
            logging.config.fileConfig('logger.ini')
        else:
            logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
            logger.info('Using default log configuration; override in a config.ini')

    def start(self) -> None:
        create_config()

        Config.load("config.yml")

        try:
            commands = list(Config.get("Commands").values())
        except Exception:
            logger.warn('No commands configured')
            commands = []

        if self.cli:
            # Execute correct command
            CommandLoader(namespaces=commands)


App(__name__ == "__main__").start()
