#!/usr/bin/env python
"""
 Copyright (C) 2010 David Francos Cuartero
        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 2
        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, write to the Free Software
        Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

"""
from Digenpy_ import *
import sys, Digenpy_, types, pygtk, gtk, gobject
from gettext import gettext as _

class BasicDicts:
    def __init__(self):
        self.z=[]

    def get_companies(self, country):
        c=[]
        mod=getattr(Digenpy_, country)
        for a in dir(mod):
            if isinstance(getattr(mod, a, None), types.ClassType):
                help_=getattr(mod, a)('').dictionary
                if help_:
                    c.append(a)
        return c

    def generate(self, country, company, fo, bssid, essid):
        module=getattr(Digenpy_, country)
        self.printer(fo, getattr(module, company)(['gui', bssid, essid]).dictionary)

    def printer(self, fo, a_print):
        for a in a_print:
            fo.write(a)
            fo.write('\n')

class MainGUI:
    def __init__(self):
        self.dicts=BasicDicts()

        self.builder=gtk.Builder()
        self.builder.add_from_file(sys.prefix + '/share/digenpy.ui')
        self.widgets=self.builder
        self.window=self.builder.get_object('MainWindow')

        self.widgets.connect_signals({
                'on_button_ok_clicked': self.generate,
                'on_button_cancel_clicked': gtk.main_quit,
                'on_country_selected': self.populate_companies,
                'on_ignore_clicked': self.destroy_dialog
                })

        self.company=self.widgets.get_object('company')
        self.country=self.update_combobox(Digenpy_.__all__, self.widgets.get_object('country'))
        self.except_window=self.builder.get_object('ErrorWindow')
        sys.excepthook = self.exception_handler
        self.window.show()

    def destroy_dialog(self, widgets):
        self.except_window.hide()

    def exception_handler(self, type_, value, traceback):
        self.widgets.get_object('message').set_label(value.__str__())
        self.except_window.show()

    def update_combobox(self, dict_, widget):
        model = gtk.ListStore(gobject.TYPE_STRING)
        for entry in dict_:
            model.append([entry])
        widget.set_model(None)
        widget.set_model(model)
        cell = gtk.CellRendererText()
        widget.pack_start(cell, True)
        widget.add_attribute(cell, 'text',0)
        return widget

    def populate_companies(self, widgets):
        self._country=self.country.get_model()[self.country.get_active()][0]
        self.company=self.update_combobox(self.dicts.get_companies(self._country), self.company)

    def generate(self, widgets):
        bssid=self.widgets.get_object('bssid').get_text()
        essid=self.widgets.get_object('essid').get_text()
        file_=self.widgets.get_object('file').get_text()

        try:
            self._company=self.company.get_model()[self.company.get_active()][0]
        except:
            pass
        if not bssid or not essid or not file_ or not self._company or not self._country:
            raise Exception(_('Error: Some of the needed data is missing\nMake sure you\'ve entered the bssid, essid and destfile, as well as company and country'))

        self.dicts.generate(self._country, self._company, open(file_,'a+'), bssid, essid)
        raise Exception(_('Dicts correctly generated in ') + file_)

if __name__== "__main__":
    MainGUI()
    gtk.main()
