#!/usr/bin/env python

import os
import sys
import apt
from user import home
import gettext
import gtk
import gtk.glade
import commands

def addListColumn(view, title, columnId):
    column = gtk.TreeViewColumn(title, gtk.CellRendererText(), text=columnId)
    column.set_resizable(True)
    column.set_sort_column_id(columnId)
    view.append_column(column)

def onRowActivated(widget, path, column):
    model=widget.get_model()
    iter = model.get_iter(path)
    name = model.get_value(iter, 1)
    os.system("/usr/lib/solydxk/softwaremanager/make-cmd " + name + " &")

# i18n
gettext.install("solydxk-softwaremanager", "/usr/share/locale")

suggestion = sys.argv[1]

gladefile = "/usr/share/solydxk/softwaremanager/suggestions.glade"
wTree = gtk.glade.XML(gladefile,"window_dialog_list")
wTree.get_widget("window_dialog_list").set_icon_from_file("/usr/share/solydxk/softwaremanager/icon.svg")
wTree.get_widget("window_dialog_list").set_title("apt search " + suggestion)
wTree.get_widget("window_dialog_list").connect("destroy", gtk.main_quit)
wTree.get_widget("label_no_results").set_text(_("No results"))
lview = wTree.get_widget("listview")

column = gtk.TreeViewColumn(_("Installed"), gtk.CellRendererToggle(), active=0)
column.set_resizable(True)
column.set_sort_column_id(0)
lview.append_column(column)
addListColumn(lview, _("Package"), 1)
addListColumn(lview, _("Description"), 2)
lstore = gtk.ListStore(bool, str, str)
lview.set_model(lstore)
result = commands.getoutput("aptitude search " + suggestion)
results = str.split(result, "\n")
foundAny = False
for result in results:
    if (result != ""):
        foundAny = True
        state = result[:4]
        for i in [["p", 0], ["c", 0], ["i", 1], ["v", -1]]:
            if state[0] == i[0]:
                state = i[1]
                break
        # if package is virtual, skip it - virtual packages should be handled in Synaptic
        if state == -1:
            continue
        package = result.split(' - ')[0][4:].strip()
        description = result.split(' - ')[1].strip()
        lstore.append([state, package, description])
if (not foundAny):
    # Switch the notebook to show the "No results" page
    wTree.get_widget("notebook_list").set_current_page(1)

lview.connect("row-activated", onRowActivated);
wTree.get_widget("window_dialog_list").show()

gtk.main()
