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

###############################################################################
#  Copyright Kitware Inc.
#
#  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.
###############################################################################
"""
This script provides a simple interface for installing optional components
for girder.  Try `girder-install --help` for more information.
"""

import sys
import os
import argparse
from six import StringIO

stdout = sys.stdout
stderr = sys.stderr

try:
    sys.stdout = StringIO()
    sys.stderr = StringIO()
    from girder import constants
    from girder.utility.plugin_utilities import getPluginDir
    from girder.utility.install import install_plugin, install_web
    sys.stdout = stdout
    sys.stderr = stderr
except ImportError:
    stderr.write(
        'Could not import girder.  Please ensure that your PYTHONPATH is correct.\n'
    )
    sys.exit(1)

pluginDir = getPluginDir()
webRoot = os.path.join(constants.STATIC_ROOT_DIR, 'clients', 'web')
version = constants.VERSION['apiVersion']


def handle_web(parser):
    """
    Handles the object returned by argparse for the `web` command.
    """
    result = install_web(parser.source, parser.force)
    if not result:
        sys.stderr.write(
            'Could not install client libraries from "{}".\n'.format(parser.source)
        )
        sys.exit(1)
    else:
        print('Installed client libraries to "{}"'.format(result))


def handle_plugin(parser):
    """
    Handles the object returned by argparse for the `plugin` command.
    """
    result = install_plugin(parser.source, parser.force)
    if not len(result):
        sys.stderr.write(
            'Could not install plugins from "{}".\n'.format(parser.source)
        )
        sys.exit(1)
    else:
        print('Installed {} plugins:'.format(len(result)))
        print('  ' + '\n  '.join(result))


def print_version(parser):
    """
    Prints the girder version number.
    """
    print(version)


def print_plugin_path(parser):
    """
    Prints the configured plugin path.
    """
    print(pluginDir)


def print_web_root(parser):
    """
    Prints the static web root.
    """
    print(webRoot)


def main(args):
    """
    Main function that parses the argument list and delagates to the correct function
    using the argparse package.
    """
    parser = argparse.ArgumentParser(
        description='Install optional Girder components.  To get help for a subcommand, '
                    'try "{} <command> -h"'.format(args[0]),
        epilog='This script supports installing from a url, a tarball, '
               'or a local path.  When installing with no sources specified, it will install '
               'from the main Girder repository corresponding to the Girder release '
               'currently installed.'
    )

    parser.add_argument(
        '-f', '--force',
        action='store_true',
        help='Overwrite existing files'
    )

    sub = parser.add_subparsers()

    plugin = sub.add_parser(
        'plugin',
        help='Install plugins.'
    )
    plugin.set_defaults(func=handle_plugin)

    web = sub.add_parser(
        'web',
        help='Install web client libraries.'
    )
    web.set_defaults(func=handle_web)

    sub.add_parser(
        'version',
        help='Print the currently installed version of Girder.'
    ).set_defaults(func=print_version)

    sub.add_parser(
        'plugin-path',
        help='Print the currently configured plugin path.'
    ).set_defaults(func=print_plugin_path)

    sub.add_parser(
        'web-root',
        help='Print the currently web root for static files.'
    ).set_defaults(func=print_web_root)

    plugin.add_argument(
        '-s', '--source',
        help='A directory, tarball, or url to a tarball containing one or more '
             'plugins.  Defaults to installing all plugins in the Girder repository'
    )

    web.add_argument(
        '-s', '--source',
        help='A directory, tarball, or url to a tarball containing client '
             'side content.  Defaults to installing client libraries from the '
             'currently installed Girder release.'
    )

    parsed = parser.parse_args(args[1:])
    parsed.func(parsed)

if __name__ == '__main__':
    import sys
    main(sys.argv)
