#!/usr/pkg/bin/python2.7

import gtk, re, cb_extras
from gettext import gettext as _
from convert import frac_to_float
import gobject

class TimeEntry (gtk.HBox,gobject.GObject):

    units = [_('seconds'),_('minutes'),_('hours'),_('days'),_('weeks'),_('months')]

    __gsignals__ = {
        'mnemonic-activate' :'override'
        }
    def __init__ (self, *args, **kwargs):
        gobject.GObject.__init__(self, *args, **kwargs)
        self.adj = gtk.Adjustment(value=0, lower=0, upper=100, step_incr=1, page_incr=10)
        self.spin = gtk.SpinButton(adjustment=self.adj, digits=1)
        self.spin.set_numeric(True)
        self.spin.set_update_policy(gtk.UPDATE_IF_VALID)        
        self.combo = gtk.ComboBoxEntry()
        cb_extras.set_model_from_list(self.combo,self.units)
        #self.combo.set_popdown_strings(self.units)
        self.pack_start(self.spin, True, True)
        self.spin.show()
        self.pack_start(self.combo, True, True, 6)
        self.combo.show()
        #self.combo.entry.set_text(_('minutes'))
        cb_extras.cb_set_active_text(self.combo,_('minutes'))        
        
    def do_mnemonic_activate (self,*args):
        self.spin.grab_focus()
        return True

    def set_text (self, text):
        """We only accept text of the form '# unit'"""
        try:
            num,unit = text.split()
        except:
            num,unit = 0,_('minutes') #defaults
        try:
            self.spin.set_value(float(num))
        except ValueError:
            flnum = frac_to_float(num)
            if flnum:
                self.spin.set_value(flnum)
            else:
                print "Having trouble parsing time: ",num,' (part of ',text,')'
        self.combo.entry.set_text(str(unit))
        
    def get_text (self):
        """We return text in the form of '# unit'"""
        num,unit=self.get_value()
        if num:
            if int(num)==num: num=int(num)
            return "%s %s"%(num,unit)
        else: return ""

    def get_value (self):
        """We return a tuple #,unit"""
        return (self.spin.get_value(),self.combo.entry.get_text())

    def set_value (self, number, unit):
        self.spin.set_value(float(number))
        self.combo.entry.set_text(str(unit))

    def connect (self, signal, handler):
        self.spin.connect(signal, handler)
        self.combo.entry.connect(signal, handler)

        
if gtk.pygtk_version[1] < 8: gobject.type_register(TimeEntry)
        
def makeTimeEntry ():
    te=TimeEntry()
    te.show()
    return te

if __name__ == '__main__':
    w=gtk.Window()
    te=TimeEntry()
    w.add(te)
    te.show()
    w.show()
    w.connect('delete_event',gtk.main_quit)
    gtk.main()
    
