#!/usr/bin/python
# -*- coding: utf-8 -*-
#   WillowNG - Content Filtering Web Proxy
#   Copyright (C) 2006  Travis Watkins
#
#   This library is free software; you can redistribute it and/or
#   modify it under the terms of the GNU Library General Public
#   License as published by the Free Software Foundation; either
#   version 2 of the License, or (at your option) any later version.
#
#   This library 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
#   Library General Public License for more details.
#
#   You should have received a copy of the GNU Library General Public
#   License along with this library; if not, write to the Free Software
#   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

import gtk, gtk.glade, gobject
import dbus
import urllib2
import commands
import gettext
import os
from WillowNG import util
gettext.bindtextdomain('alacarte')
gettext.textdomain('alacarte')
gtk.glade.bindtextdomain('alacarte')
gtk.glade.textdomain('alacarte')
_ = gettext.gettext

class MainWindow:
    def __init__(self):
        try:
            from WillowNG import config
            datadir = config.pkgdatadir
            self.confdir = config.confdir
        except:
            datadir = '.'
            self.confdir = '.'
        self.config = util.readConfig(self.confdir, datadir)
        self.tree = gtk.glade.XML(os.path.join(datadir, 'willowng.glade'))
        self.tree.get_widget('content_filter_button').set_filename(os.path.abspath(self.config['content_blocked_page']))
        self.tree.get_widget('domain_filter_button').set_filename(os.path.abspath(self.config['domain_blocked_page']))
        mainwin = self.tree.get_widget('mainwindow')
        if os.path.exists('/usr/share/pixmaps/willowng.png'):
            mainwin.set_icon_from_file('/usr/share/pixmaps/willowng.png')
        signals = {}
        for attr in dir(self):
            signals[attr] = getattr(self, attr)
        self.tree.signal_autoconnect(signals)
        try:
            bus = dbus.SystemBus()
            remote_object = bus.get_object('com.ubuntu.WillowNG', '/com/ubuntu/WillowNG')
            self.iface = dbus.Interface(remote_object, 'com.ubuntu.WillowNG')
            self._setupDomainLists()
        except:
            mainwin.set_sensitive(False)
            dialog = gtk.MessageDialog(parent=mainwin, flags=gtk.DIALOG_DESTROY_WITH_PARENT, type=gtk.MESSAGE_ERROR, buttons=gtk.BUTTONS_YES_NO)
            dialog.set_title('')
            dialog.set_markup(_('Content filter not running! Start content filter?'))
            response = dialog.run()
            if response == gtk.RESPONSE_YES:
                commands.getoutput('/etc/dbus-1/event.d/99willowng start')
                os.execvp('willowng-config', ())
            else:
                mainwin.destroy()

    def _setupDomainLists(self):
        good_list = self.tree.get_widget('good_domain_list')
        self.good_store = gtk.TreeStore(str)
        column = gtk.TreeViewColumn(_('Domain'))
        cell = gtk.CellRendererText()
        column.pack_start(cell)
        column.set_attributes(cell, text=0)
        good_list.append_column(column)
        good_list.set_model(self.good_store)

        bad_list = self.tree.get_widget('bad_domain_list')
        self.bad_store = gtk.TreeStore(str)
        column = gtk.TreeViewColumn(_('Domain'))
        cell = gtk.CellRendererText()
        column.pack_start(cell)
        column.set_attributes(cell, text=0)
        bad_list.append_column(column)
        bad_list.set_model(self.bad_store)
        self._loadDomainLists()

    def _loadDomainLists(self):
        self.good_store.clear()
        self.bad_store.clear()
        domains = self.iface.getDomains()
        if domains == None:
            return
        for domain in domains:
            if domain[1] == 'bad':
                self.bad_store.append(None, (domain[0],))
            elif domain[1] == 'good':
                self.good_store.append(None, (domain[0],))

    def addDomain(self, pool):
        mainwindow = self.tree.get_widget('mainwindow')
        if pool == 'bad':
            title = _('Add Bad Domain')
        else:
            title = _('Add Good Domain')
        dialog = gtk.Dialog(title, mainwindow, gtk.DIALOG_MODAL|gtk.DIALOG_DESTROY_WITH_PARENT|gtk.DIALOG_NO_SEPARATOR,(gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT, gtk.STOCK_ADD, gtk.RESPONSE_ACCEPT))
        hbox = gtk.HBox()
        hbox.set_spacing(6)
        hbox.set_border_width(4)
        label = gtk.Label(_('Domain: '))
        entry = gtk.Entry()
        hbox.add(label)
        hbox.add(entry)
        dialog.vbox.add(hbox)
        hbox.show()
        entry.show()
        label.show()
        response = dialog.run()
        if response == gtk.RESPONSE_ACCEPT:
            domain = entry.get_text()
            if pool == 'bad':
                self.iface.domainBad(domain)
            else:
                self.iface.domainGood(domain)
        dialog.destroy()

    def on_content_filter_button_selection_changed(self, button):
        filename = button.get_filename()
        if filename != None and filename != self.config['content_blocked_page']:
            self.config['content_blocked_page'] = filename
            util.writeConfig(self.confdir, self.config)

    def on_domain_filter_button_selection_changed(self, button):
        filename = button.get_filename()
        if filename != None and filename != self.config['domain_blocked_page']:
            self.config['domain_blocked_page'] = filename
            util.writeConfig(self.confdir, self.config)

    def on_add_good_button_clicked(self, button):
        self.addDomain('good')
        self._loadDomainLists()

    def on_remove_good_button_clicked(self, button):
        good_list = self.tree.get_widget('good_domain_list')
        domains, iter = good_list.get_selection().get_selected()
        self.iface.removeDomain(domains[iter][0])
        self.tree.get_widget('remove_good_button').set_sensitive(False)
        self._loadDomainLists()

    def on_good_domain_list_cursor_changed(self, good_list):
        self.tree.get_widget('remove_good_button').set_sensitive(True)

    def on_add_bad_button_clicked(self, button):
        self.addDomain('bad')
        self._loadDomainLists()

    def on_remove_bad_button_clicked(self, button):
        bad_list = self.tree.get_widget('bad_domain_list')
        domains, iter = bad_list.get_selection().get_selected()
        self.iface.removeDomain(domains[iter][0])
        self.tree.get_widget('remove_bad_button').set_sensitive(False)
        self._loadDomainLists()

    def on_bad_domain_list_cursor_changed(self, good_list):
        self.tree.get_widget('remove_bad_button').set_sensitive(True)

    def on_good_url_button_clicked(self, button):
        url = self.tree.get_widget('good_url_entry').get_text()
        self.iface.trainGood(url)

    def on_bad_url_button_clicked(self, button):
        url = self.tree.get_widget('bad_url_entry').get_text()
        self.iface.trainBad(url)

    def on_mainwindow_destroy(self, widget):
        gtk.main_quit()

    def on_close_button_clicked(self, button):
        self.on_mainwindow_destroy(button)

if os.getuid() != 0:
    dialog = gtk.MessageDialog(type=gtk.MESSAGE_ERROR, buttons=gtk.BUTTONS_CLOSE)
    dialog.set_title('')
    dialog.set_markup(_('This program must be run as superuser.'))
    response = dialog.run()
    gobject.timeout_add(0, gtk.main_quit)

foo = MainWindow()
gtk.main()
