#!/usr/bin/python2.7
# -*- coding: utf-8 -*-

#   Copyright (C) 2012 P.L. Lucas
#
#    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 3 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, see <http://www.gnu.org/licenses/>.

import shlex, subprocess
import pygtk
pygtk.require('2.0')
import gtk
import os


class USBsGUI:


	def delete_event(self, widget, event, data=None):
		# If you return FALSE in the "delete_event" signal handler,
		# GTK will emit the "destroy" signal. Returning TRUE means
		# you don't want the window to be destroyed.
		# This is useful for popping up 'are you sure you want to quit?'
		# type dialogs.
		#print "delete event occurred"
		
		#print self.get_devices_list()

		# Change FALSE to TRUE and the main window will not be destroyed
		# with a "delete_event".
		return False

	def destroy(self, widget, data=None):
		#print "destroy signal occurred"
		gtk.main_quit()
	
	def get_active_text(self, combobox):
		model = combobox.get_model()
		active = combobox.get_active()
		if active < 0:
			return None
		return model[active][0]
	
	def get_devices_list(self):
		model=self.seats_treeview.get_model()
		seats_usbs_list=[]
		n=0
		for seat_iter in self.iter_seats_list:
			if model.iter_has_child(seat_iter):
				usb_iter=model.iter_children(seat_iter)
			else:
				usb_iter=None
			seats_usbs_list.append([])
			x=0
			while usb_iter!=None:
				seats_usbs_list[n].append(str(model[usb_iter][0]))
				x+=1
				usb_iter=model.iter_next(usb_iter)
			n+=1
		return seats_usbs_list

	
	def delete_callback(self, widget, data=None):
		(model_usb, iter_usb) = self.ubs_treeview.get_selection().get_selected()
		usb=model_usb.get_value(iter_usb,0)
		command='udisksctl unmount -b {0}'.format(usb)
		##command='umount {0}'.format(usb)
		os.system(command)
		command='udisksctl power-off -b {0}'.format(usb)
		ok=os.system(command)
		self.reload_callback(widget)
		if ok!=0:
			md = gtk.MessageDialog(self.window, gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_INFO,  gtk.BUTTONS_CLOSE, "Error: No se pudo extraer el dispositivo")
			md.run()
			md.destroy()
	
	def reload_callback(self, widget, data=None):
		model=self.ubs_treeview.get_model()
		iters=[]
		itera=model.get_iter_first()
		while itera!=None:
			iters.append(itera)
			itera=model.iter_next(itera)
		for itera in iters:
			path = model.get_path(itera)
			model.remove(itera)
			model.row_deleted(path)
		for usb in usb_list():
			model.append(None, usb)
	
	def init_treeview(self, labels):
		treestore = gtk.TreeStore(str, str)
		# create the TreeView using treestore
		treeview = gtk.TreeView(treestore)
		n=0
		for label in labels:
			# create the TreeViewColumn to display the data
			tvcolumn = gtk.TreeViewColumn(label)
			# add tvcolumn to treeview
			treeview.append_column(tvcolumn)
			# create a CellRendererText to render the data
			cell = gtk.CellRendererText()
			# add the cell to the tvcolumn and allow it to expand
			tvcolumn.pack_start(cell, True)
			# set the cell "text" attribute to column n - retrieve text
			# from that column in treestore
			tvcolumn.add_attribute(cell, 'text', n)
			n+=1
		# make it searchable
		treeview.set_search_column(0)
		# Allow sorting on the column
		tvcolumn.set_sort_column_id(0)
		treeview.get_selection().set_mode(gtk.SELECTION_SINGLE)
		return treeview
	
	def init_gui_area(self):
		# create the TreeView using treestore
		self.ubs_treeview = self.init_treeview(['Dispositivos USB Conectados', 'Directorio de Montaje'])
		
		#self.scrolled_window=self.init_usb_list_gui()
		vbox=gtk.VBox()
		hbox=gtk.HBox()
		vbox.pack_start(hbox, True, True)
		vbox1=gtk.VBox()
		
		hbox.pack_start(vbox1, True, True)
		
		scrolled_window = gtk.ScrolledWindow(hadjustment=None, vadjustment=None)
		scrolled_window.add_with_viewport(self.ubs_treeview)
		scrolled_window.show()
		vbox1.pack_start(scrolled_window, True, True)
		
		remove_button=gtk.Button(stock=gtk.STOCK_REMOVE)
		remove_button.connect("clicked", self.delete_callback, None)
		vbox1.pack_start(remove_button, False, False)
		remove_button.show()
		
		refresh_button=gtk.Button(stock=gtk.STOCK_REFRESH)
		refresh_button.connect("clicked", self.reload_callback, None)
		vbox1.pack_start(refresh_button, False, False)
		refresh_button.show()
		refresh_button.connect("clicked", self.reload_callback, None)
		
		hbox.show_all()
		vbox1.show_all()
		vbox.show_all()
		
		return vbox

	def __init__(self):
		pass
	
	def init_window(self):
		# create a new window
		self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)

		# When the window is given the "delete_event" signal (this is given
		# by the window manager, usually by the "close" option, or on the
		# titlebar), we ask it to call the delete_event () function
		# as defined above. The data passed to the callback
		# function is NULL and is ignored in the callback function.
		self.window.connect("delete_event", self.delete_event)

		# Here we connect the "destroy" event to a signal handler.  
		# This event occurs when we call gtk_widget_destroy() on the window,
		# or if we return FALSE in the "delete_event" callback.
		self.window.connect("destroy", self.destroy)

		# Sets the border width of the window.
		self.window.set_border_width(10)

		# This packs the button into the window (a GTK container).
		self.window.add(self.init_gui_area())

		# and the window
		# Dimensiones de la ventana: Ancho x Alto
		self.window.resize(500,300)
		self.window.show()
		self.reload_callback(None)

	def main(self):
		# All PyGTK applications must have a gtk.main(). Control ends here
		# and waits for an event to occur (like a key press or mouse event).
		gtk.main()



#This function looks for usb pendrives connected to this computer and returns a list with host plugged
def usb_list():
	usb_list=parse_udisks_dump()
	return usb_list

def parse_udisks_dump():
	#command_line='udisksctl dump'
	command_line='udisks --dump'
	pipe = subprocess.Popen(command_line, shell=True, bufsize=256, stdout=subprocess.PIPE).stdout
	lines=pipe.readlines()
	pipe.close()
	usb_list=[]
	last_device=None
	for line in lines:
		if 'presentation:' in line:
			last_device=line[line.find('/'):line.find('\n')]
		elif 'mount paths:' in line and '/media' in line:
			usb=[last_device]
			usb.append( line[line.find('/'):line.find('\n')] )
			usb_list.append(usb)
	return usb_list


if __name__ == "__main__":
	gui = USBsGUI()
	gui.init_window()
	gui.main()

#print usb_list()



