# -*- coding: utf-8 -*-
### BEGIN LICENSE
# Copyright (C) 2009 Jono Bacon <jono@ubuntu.com>
# Copyright (C) 2010 Michael Budde <mbudde@gmail.com>
#
#This program is free software: you can redistribute it and/or modify it
#under the terms of the GNU General Public License version 3, as published
#by the Free Software Foundation.
#
#This program is distributed in the hope that it will be useful, but
#WITHOUT ANY WARRANTY; without even the implied warranties of
#MERCHANTABILITY, SATISFACTORY QUALITY, 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/>.
### END LICENSE

import os
import gtk
import ConfigParser
import gobject
import urllib
import xdg.BaseDirectory
import logging

from lernid.lernidconfig import get_data_path, save_cache_path

class ConnectDialog(gtk.Dialog):
    __gtype_name__ = "ConnectDialog"

    def __init__(self):
        """__init__ - This function is typically not called directly.
        Creation of a ConnectDialog requires redeading the associated ui
        file and parsing the ui definition extrenally,
        and then calling ConnectDialog.finish_initializing().

        Use the convenience function NewConnectDialog to create
        a ConnectDialog object.

        """
        gtk.Dialog.__init__(self)

    def finish_initializing(self, builder):
        """finish_initalizing should be called after parsing the ui definition
        and creating a ConnectDialog object with it in order to finish
        initializing the start of the new ConnectDialog instance.

        """
        # FIXME: avoid circular import
        from lernid.EventManager import EventManager

        #get a reference to the builder and set up the signals
        self.builder = builder
        self.builder.connect_signals(self)

        store = gtk.ListStore(gobject.TYPE_STRING)
        eventman = EventManager.get_instance()
        self._eventlist=[]
        for s in eventman.get_available_events():
            store.append([s])
            self._eventlist += [unicode(s),]

        self.event_combo = self.builder.get_object("event_combo")
        self.event_combo.set_model(store)
        cell = gtk.CellRendererText()
        self.event_combo.pack_start(cell, True)
        self.event_combo.add_attribute(cell, 'text',0)
        if len(store) > 0:
            self.event_combo.set_active(0)

    def ok(self, widget, data=None):
        """ok - The user has elected to save the changes.
        Called before the dialog returns gtk.RESONSE_OK from run().
        """
        self.hide()
        self.event_combo.grab_focus()

    def cancel(self, widget, data=None):
        """cancel - The user has elected cancel changes.
        Called before the dialog returns gtk.RESPONSE_CANCEL for run()
        """
        self.hide()
        self.event_combo.grab_focus()

    def check_ready_to_connect(self, widget):
        event_combo = self.builder.get_object("event_combo")
        nick_textentry = self.builder.get_object("nick_textentry")
        if self.is_valid_nick(nick_textentry) and (event_combo.get_active() != -1) :
            self.builder.get_object("button_connect").set_sensitive(True)
        else:
            self.builder.get_object("button_connect").set_sensitive(False)

    def get_nick(self):
        return self.builder.get_object('nick_textentry').get_text()

    def set_nick(self, nick):
        return self.builder.get_object('nick_textentry').set_text(nick)

    def get_event(self):
        return self.builder.get_object('event_combo').get_active_text()

    def set_event(self, event):
        if not event in self._eventlist:
            return False
        index = self._eventlist.index(event)
        return self.builder.get_object('event_combo').set_active(index)

    def get_password(self):
        return self.builder.get_object('password').get_text()

    def is_valid_nick(self, nick_te):
        alpha = 'abcdefghijklmnopqrstuvwxyz'
        alpha = alpha + alpha.upper()
        numeric = '0123456789'
        symbol = '_-[]\\`^{}|'
        nick = nick_te.get_text()
        if nick == "":
            nick_te.set_tooltip_text(_("Nick can not be blank"))
            return False
        try:
            if nick[0] not in alpha + symbol:
                nick_te.set_tooltip_text(_("Nick can not begin with: %s" % (nick[0])))
                return False
            for c in nick[1:]:
                if c not in alpha + numeric + symbol:
                    nick_te.set_tooltip_text(_("Nick can not contain blank spaces.") if c == ' ' else _("Nick can not contain: %s" % (c)))
                    return False
        except UnicodeDecodeError:
            nick_te.set_tooltip_text(_("Nick can only contain English alphabet characters"))
            return False
        nick_te.set_tooltip_text(None)
        return True

def NewConnectDialog():
    """NewConnectDialog - returns a fully instantiated
    dialog-camel_case_nameDialog object. Use this function rather than
    creating ConnectDialog instance directly.

    """

    #look for the ui file that describes the ui
    ui_filename = get_data_path('ui', 'ConnectDialog.ui')
    builder = gtk.Builder()
    builder.add_from_file(ui_filename)
    dialog = builder.get_object("connect_dialog")
    dialog.finish_initializing(builder)
    return dialog

if __name__ == "__main__":
    dialog = NewConnectDialog()
    dialog.show()
    gtk.main()

