#!/usr/bin/python

import sys
import os
import gtk
import gtk.glade
import gobject
import urllib2

from gettext import gettext as _
import gettext
import locale

from hwdb_client import Constants
from hwdb_client import ClientForm

localesApp="hwdb-client"
localesDir="/usr/share/locale"
locale.setlocale(locale.LC_ALL, '')
gettext.bindtextdomain(localesApp, localesDir)
gettext.textdomain(localesApp)

tree=gtk.glade.XML (Constants.DATADIR + "/send.glade","window1","hwdb-client")
timeout = 10
server = 'hwdb.ubuntu.com'

win = tree.get_widget("window1")
win.set_icon_from_file(Constants.DATADIR + "/ubuntu_logo.png")

cancel = tree.get_widget("button1")
ok = tree.get_widget("button2")
pbar = tree.get_widget("progressbar1")

class Sender:
    def __init__(self):
	
	cancel.connect("clicked", lambda w: gtk.main_quit())
	win.connect("destroy", lambda w: gtk.main_quit())
	ok.connect("clicked", lambda w: self.connect())
	ok.grab_focus()
	
	win.set_position(gtk.WIN_POS_CENTER)
	win.show_all()

    def main(self):
            gtk.main()

    def connect(self):
	pbar.set_text(_("Connecting to server (timeout 30sec)"))
	while gtk.events_pending():
	    gtk.main_iteration(True)

	command = 'fping -a '+server+' 2>/dev/null'
	home_path=os.environ["HOME"]
	lock = open(home_path+'/.hwdb', 'w')
	md5sum = []
	ping = ''

	for line in os.popen(command):
		ping = line
	print ping

        for line in os.popen('md5sum /tmp/hwdb_data.xml'):
	    md5sum = line.split(' ')
        os.system('mv /tmp/hwdb_data.xml /tmp/'+md5sum[0]+'.xml')
	os.system('bzip2 /tmp/'+md5sum[0]+'.xml')
	
	if not ping:
	    dialog = gtk.MessageDialog(None, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR, gtk.BUTTONS_CLOSE,
	          		_("Can not connect to server, a copy of the data will get dropped\n to your desktop, please send it as mail\n attachment to hwdb@ubuntu.com"))
	    dialog.run()
	    dialog.destroy()
	    while gtk.events_pending():
	        gtk.main_iteration(True)
	    pbar.set_text("Copying to desktop")
	    os.system('mv /tmp/'+md5sum[0]+'.xml.bz2 ~/Desktop/')
	    self.timeout = gobject.timeout_add (50, lambda w: self.pulsator(), self)
	    self.timeout = gobject.timeout_add (500, lambda w: gtk.main_quit(), self)
	else:
	   request = urllib2.Request('http://'+server+'/upload/')
 	   response = urllib2.urlopen(request)
 	   forms = ClientForm.ParseResponse(response)
 	   form = forms[0]
    	   form.add_file(open('/tmp/'+md5sum[0]+'.xml.bz2'), 'text/xml', md5sum[0]+'.xml.bz2')
 	   response.close()
	   request2 = form.click()
    	   response2 = urllib2.urlopen(request2)
	   self.transmit()
	lock.write(md5sum[0])
	lock.close()
	os.system('rm /tmp/'+md5sum[0]+'.xml*')
	
    def pulsator(self):
	pbar.pulse()
	return True

    def transmit(self):
   	cancel.set_sensitive(False)
	ok.set_sensitive(False)
	pbar.set_text(_("Sending data..."))
	self.timer = gobject.timeout_add (3000, lambda w: self.timings(), self)
	
    def timings(self):
	self.timer = gobject.timeout_add (50, lambda w: self.pulsator(), self)
	self.timeout = gobject.timeout_add (5000, lambda w: gtk.main_quit(), self)

if __name__ == "__main__":

    base = Sender()
    base.main()
