#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# fuss-launcher command line testing tool
#
# Copyright (C) 2010 Enrico Zini <enrico@truelite.it>
# Copyright (C) 2010 Christopher R. Gabriel <cgabriel@truelite.it>
# Copyright (C) 2010 The Fuss Project <info@fuss.bz.it>
#
# Authors: Christopher R. Gabriel <cgabriel@truelite.it>
#          Enrico Zini <enrico@truelite.it>
#
# Sponsored by the Fuss Project: http://www.fuss.bz.it/
#
# This program 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.
#
# This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.

import os, os.path
import sys
import fusslauncher
import fusslauncher.conf as conf
import fusslauncher.appinfo as appinfo
import readline

import gettext
_ = gettext.gettext

class Completer(object):
    def __init__(self, engine):
        self.engine = engine
        self.completions = []

    def __call__(self, text, state):
        if state == 0:
            query = readline.get_line_buffer()
            pfxlen = len(query) - len(text)
            self.engine.set_query(query)
            self.completions = [x[pfxlen:] for x in self.engine.completions()]
        if state > len(self.completions): return None
        return self.completions[state]

class Cmdline(object):
    def __init__(self, opts):
        self.engine = fusslauncher.Engine()
        self.engine.set_install_only(not opts.uninstalled)
        self.app_cache = appinfo.AppInfoCache()

    def print_query_results(self, query):
        print "Results for %s:" % repr(query)
        self.engine.set_query(query, [])
        for res in self.engine.documents():
            app = self.app_cache[res[1]]
            print "  %02d%% %s (%sinstalled)" % (res[0], app.name, "not " if not app.inst else "")
            print "      D: %s" % app.dpath
            print "      I: %s" % app.ipath

    def print_completion_results(self, query):
        print "Completions for %s:" % repr(query)
        self.engine.set_query(query, [])
        for res in self.engine.completions():
            print " ", res

    def do_interactive_console(self):
        # I would like to use cmd. But I cannot use cmd because it *always* strips
        # entered lines, and our queries instead change depending on trailing spaces.

        readline.parse_and_bind("tab: complete")
        readline.set_completer(Completer(self.engine))

        print "Welcome to the fuss-launcher test interface version %s." % conf.VERSION
        print
        print "Please type your queries, end with ^D."
        print
        while True:
            try:
                query = raw_input("> ")
            except EOFError:
                print
                print "Bye."
                break
            self.print_query_results(query)

from fusslauncher import cmdline

parser = cmdline.Parser(usage="usage: %prog [options]",
                description="Fuss application launcher debug tool")
parser.add_option("-q", "--quiet", action="store_true", help="quiet mode: only output fatal errors")
parser.add_option("-v", "--verbose", action="store_true", help="verbose mode")
parser.add_option("-d", "--debug", action="store_true", help="debug mode")
parser.add_option("-u", "--uninstalled", action="store_true", help="debug mode")
(opts, args) = parser.parse_args()

gettext.bindtextdomain(conf.GETTEXT_PACKAGE)
gettext.textdomain(conf.GETTEXT_PACKAGE)

if opts.debug:
    import fusslauncher.engine
    fusslauncher.engine.debug = True

cmd = Cmdline(opts)
if args:
    qstring = " ".join(args)
    cmd.print_query_results(qstring)
    cmd.print_completion_results(qstring)
else:
    cmd.do_interactive_console()

sys.exit(0)
