#!/usr/bin/env python
# PYTHON_ARGCOMPLETE_OK
"""
Copyright 2010-2014 DIMA Research Group, TU Berlin

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.

Created on Apr 13, 2014
"""

import sys
import os

# ######################################################################################################################
# Determine paths
# ######################################################################################################################

if 'HOME' in os.environ:
    user_home = os.path.abspath(os.environ['HOME'])
else:
    user_home = os.path.abspath(os.path.expanduser('~'))

# ######################################################################################################################
# Sources path configuration
# ######################################################################################################################

try:
    file_name = os.readlink(__file__)
except OSError as e:
    file_name = __file__

base_path = os.path.dirname(os.path.dirname((os.path.abspath(file_name))))
if os.path.isdir(os.path.join(base_path, 'python')):
    sys.path.append(os.path.join(base_path, 'python'))

# ######################################################################################################################
# Cement Application
# ######################################################################################################################

import argcomplete
from termcolor import cprint
from cement.core import foundation, exc, handler, hook
from scrumtools import base, evaltool, github, trello


class App(foundation.CementApp):
    class Meta:
        label = 'scrum-tools'
        base_controller = base.BaseController
        arguments_override_config = True
        config_files = [
            os.path.join('/', 'etc', label, '%s.conf' % label),
            os.path.join(user_home, '.%s.conf' % label),
            os.path.join(user_home, '.%s' % label, 'config'),
            os.path.join(os.getcwd(), '.%s.conf' % label)
        ]


# noinspection PyShadowingNames
def normalize_file_schema(app):
    # make sure that 'core.users_schema' is a list
    schema = app.config.get('core', 'users_schema')
    schema = [x.strip() for x in schema.split(';')] if isinstance(schema, str) else schema
    app.config.set('core', 'users_schema', schema)
    # make sure that 'trello.board_lists' is a list
    board_lists = app.config.get('trello', 'board_lists')
    board_lists = [x.strip() for x in board_lists.split(';')] if isinstance(board_lists, str) else board_lists
    app.config.set('trello', 'board_lists', board_lists)

# create the app
app = App()

hook.register('post_argument_parsing', normalize_file_schema)

try:
    # Register any handlers that aren't passed directly to CementApp
    handler.register(evaltool.EvalToolController)
    handler.register(github.GitHubController)
    handler.register(trello.TrelloController)

    # setup the application
    app.setup()

    # register argcomplete for the application ArgumentParser
    argcomplete.autocomplete(app.args)

    # run the application
    app.run()
except RuntimeError as e:
    cprint("Error: %s" % e, 'red', attrs=['bold'], file=sys.stderr)
except exc.CaughtSignal as e:
    if e.signum == 2:
        print >> sys.stderr, ""
        cprint("Interrupted execution." % e, 'red', attrs=['bold'], file=sys.stderr)
finally:  # close the app
    app.close()

