#!/usr/bin/env python3
# Copyright 2017 The Fontbakery Authors
# Copyright 2017 The Google Font Tools Authors
#
# 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.
#
from __future__ import print_function
from argparse import RawTextHelpFormatter
from pkg_resources import get_distribution
from warnings import warn
import sys
import os
import argparse
import subprocess


def _get_subcommands():
    subcommands = {}
    scriptdir = os.path.dirname(__file__)
    for f in os.listdir(scriptdir):
        command = os.path.join(scriptdir, f)
        if not os.path.isfile(command) or not os.access(command, os.X_OK):
            continue
        if f.startswith('gftools-'):
            subcommand = f[len('gftools-'):].rsplit('.')[0]
        else:
            continue

        if subcommand in subcommands:
            warn('SKIPPING subcommand collision "{0}" subcommand "{1}" '
                 'already found as "{2}".'.format(command,
                                                  subcommand,
                                                  subcommands[subcommand]))
            continue
        subcommands[subcommand] = command
    return subcommands


def print_menu():
    __version__ = get_distribution('gftools').version
    print(" o-o              o     o--o")
    print("o                 |     |            o")
    print("| o-o o-o o-o o-o o o-o o-o o-o o-o -o- o-o")
    print("o   | | | | | | | | |-' |   | | | |  |   \\")
    print(" o-o  o-o o-o o-o o o-o o   o-o o o  o- o-o")
    print("                | Tools - Version", __version__)
    print("              o-o")
    print("\nBasic command examples:\n")
    print("    gftools compare-font font1.ttf font2.ttf")
    print("    gftools compare-font --help")
    print("    gftools --version")
    print("    gftools --help\n")


subcommands = _get_subcommands()

__version__ = get_distribution('gftools').version

description = "Run gftools subcommands:{0}".format(''.join(
              ['\n    {0}'.format(sc) for sc in sorted(subcommands.keys())]))

description += ("\n\nSubcommands have their own help messages.\n"
                "These are usually accessible with the -h/--help\n"
                "flag positioned after the subcommand.\n"
                "I.e.: gftools subcommand -h")

parser = argparse.ArgumentParser(description=description,
                                 formatter_class=RawTextHelpFormatter)
parser.add_argument('subcommand',
                    nargs=1,
                    help="the subcommand to execute")

parser.add_argument('--list-subcommands', action='store_true',
                    help='print the list of subcommnds '
                    'to stdout, separated by a space character. This is '
                    'usually only used to generate the shell completion code.')

parser.add_argument('--version', '-v', action='version',
                    version='%(prog)s ' + __version__)


if __name__ == '__main__':

    if len(sys.argv) >= 2 and sys.argv[1] in subcommands:
        # relay
        cmd = subcommands[sys.argv[1]]
        # execute ['gftools-{subcommand}'.format(sys.argv[1])] + sys.argv[2:]
        args = [cmd] + sys.argv[2:]
        p = subprocess.Popen(args, stdout=sys.stdout,
                             stdin=sys.stdin,
                             stderr=sys.stderr)
        sys.exit(p.wait())
    elif "--list-subcommands" in sys.argv:
        print(' '.join(list(subcommands.keys())))
    else:
        # shows menu and help if no args
        print_menu()
        args = parser.parse_args()
        parser.print_help()
