#!/usr/bin/python3
#
# Copyright (c) 2012-2013 - The IBus Cangjie authors
#
# This file is part of ibus-cangjie, the IBus Cangjie input method engine.
#
# ibus-cangjie is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ibus-cangjie is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with ibus-cangjie.  If not, see <http://www.gnu.org/licenses/>.

import argparse
import locale
import signal
import sys

import gi
gi.require_version('IBus','1.0')

from gi.repository import IBus

from ibus_cangjie import IMApp, EngineInfoManager


componentdir = "/usr/share/ibus/component"

try:
    locale.setlocale(locale.LC_ALL, "")
except:
    pass

parser = argparse.ArgumentParser(description="Cangjie input method engine")
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument("--ibus", "-i", action="store_true",
                    help="Start running the ibus engine. Must specify the engine to use")
group.add_argument("--engines-info", action="store_true",
                    help="Output the engines information. Can specify the engine to display")
parser.add_argument("engine", choices=("cangjie", "quick"), nargs='?', default=None,
                    help="Specify the input method engine to run or to display information about")
args = parser.parse_args()

if args.engine == 'cangjie':
    engine = 'org.freedesktop.cangjie.ibus.Cangjie'
elif args.engine == 'quick':
    engine = 'org.freedesktop.cangjie.ibus.Quick'

def signal_handler(sig, frame):
    print('You pressed Ctrl+C!')
    sys.exit(0)

signal.signal(signal.SIGINT, signal_handler)

if args.ibus:
    if args.engine == None:
        # ibus mode requires the engine to be specified
        print("Error: To start the ibus engine mode, you must specify the engine to use ('cangjie' or 'quick')\n", file=sys.stderr)
        parser.print_help(sys.stderr)
        sys.exit(1)

    # Start the ibus engine specified and connect it to ibus
    IBus.init()
    IMApp(args.ibus, args.engine, componentdir).run()

if args.engines_info:
    # Output the engines information
    m = EngineInfoManager(icondir="/usr/share/icons/hicolor/16x16/intl", bindir="/usr/bin")
    if args.engine:
        print(m.format_engines_xml(m.select_engine_by_name(args.engine)))
    else:
        print(m.format_engines_xml(m.all_engines()))
    sys.exit(0)
