#!/usr/bin/python

from gtk import *
from gnome.ui import *
from GDK import *
import libglade
from time import *	#required for printing date at top of printed shopping list
import os		#required to get location of installed glade file
import shutil		#required to copy skeleton list.txt file to user account
import string

version = '0.3'
items_selected = 0
total_items = 0

def appbar_update():
	appbar.set_status(" " + (str(items_selected)+" / "+str(total_items) + " items"))

def clear_selections(a):
	"""Clears all current selections without asking"""
	list1.unselect_all()
	list2.unselect_all()
	list3.unselect_all()
	list4.unselect_all()

def click_selection(a):
	#count selected items
	global items_selected
	selected = []
	for x in list1.get_selection():
		selected.append(x.children()[0].get())
	for x in list2.get_selection():
		selected.append(x.children()[0].get())
	for x in list3.get_selection():
		selected.append(x.children()[0].get())
	for x in list4.get_selection():
		selected.append(x.children()[0].get())
	items_selected = len(selected)
	appbar_update()
	#print list1.get_allocation()
	#print list2.get_allocation()
	#print list3.get_allocation()
	#print list4.get_allocation()
	#print list1.size_request()
	#print list2.size_request()
	#print list3.size_request()
	#print list4.size_request()

def print_master(a):
	""" Print Master list to lpr"""
	printstrings=[]
	number_of_items=0
	line=0

	for x in list1.children():
		printstrings.append(string.ljust(x.children()[0].get()[:18],19)),
		line=line+1
		number_of_items=number_of_items+1
	for x in range(4):
		"""make up extra lines if any"""
		printstrings.append(string.ljust("",19)),
		line=line+1

	line=0
	for x in list2.children():
		printstrings[line]=printstrings[line]+(string.ljust(x.children()[0].get()[:18],19))
		line=line+1
		number_of_items=number_of_items+1
	for x in range(4):
		"""make up extra lines if any"""
		printstrings[line]=printstrings[line]+(string.ljust("",19))
		line=line+1

	line=0
	for x in list3.children():
		printstrings[line]=printstrings[line]+(string.ljust(x.children()[0].get()[:18],19))
		line=line+1
		number_of_items=number_of_items+1
	for x in range(4):
		"""make up extra lines if any"""
		printstrings[line]=printstrings[line]+(string.ljust("",19))
		line=line+1

	line=0
	for x in list4.children():
		printstrings[line]=printstrings[line]+(string.ljust(x.children()[0].get()[:18],19))
		line=line+1
		number_of_items=number_of_items+1

	f = os.popen("lpr", "w")
	f.write("grocget "+ version +" Master Shopping list for " + strftime("%B %d, %Y",localtime(time())) + "\n\n")
	for x in printstrings:
		f.write(x+'\n')
	f.write('\n'+str(number_of_items) + ' items')
	f.close()





def print_selections(a):
	selected_list=[]
	for x in list1.get_selection():
		item=x.children()[0].get()
		selected_list.append(list_dic[item],item)
	for x in list2.get_selection():
		item=x.children()[0].get()
		selected_list.append(list_dic[item],item)
	for x in list3.get_selection():
		item=x.children()[0].get()
		selected_list.append(list_dic[item],item)
	for x in list4.get_selection():
		item=x.children()[0].get()
		selected_list.append(list_dic[item],item)
	if len(selected_list)<>0:
		f = os.popen("lpr", "w")
		f.write("Shopping list for " + strftime("%B %d, %Y",localtime(time())) + "\n\n")
		selected_list.sort()
		for x,y in selected_list:
			f.write(str(x+y+'\n'))
		f.write('\n'+str(items_selected) + ' items')
		f.close()

#--------- variable definitions ---------------- 
		
#----------- Program starts below ----------------
#check to see if glade file is in current directory (user must be running from download untar directory)
if  os.path.exists('grocget.glade'):
	gladefile='grocget.glade'
else:
	#look for it in the installed directory
	line = os.popen('gnome-config --datadir').readline()
	gladefile=line[:-1] + '/grocget/grocget.glade'

widgets = libglade.GladeXML(gladefile)
       
app1 = widgets.get_widget('app1')
app1.set_title('grocget-'+version+'   Grocery Getter Helper');


#--------- function definitions from classes ------------


#--------- connections to GUI ---------------- 
dic = {"on_exit1_activate": mainquit,
       "on_app1_destroy": mainquit,
       "on_button1_clicked": clear_selections,
       "on_button4_clicked": print_selections,
       "on_print_master_clicked": print_master,
       "on_list1_selection_changed": click_selection,
       "on_list2_selection_changed": click_selection,
       "on_list3_selection_changed": click_selection,
       "on_list4_selection_changed": click_selection,
       }
widgets.signal_autoconnect (dic);

list1  = widgets.get_widget('list1' )
list2  = widgets.get_widget('list2' )
list3  = widgets.get_widget('list3' )
list4  = widgets.get_widget('list4' )
appbar = widgets.get_widget('appbar1')

#check for users master grocery list
home = os.environ['HOME']
if not os.path.exists(home+'/.grocget'):
	print "Creating non-existant ~/.grocget directory to hold grocery list."
	os.mkdir(home+'/.grocget')
if not os.path.exists(home+'/.grocget/list.txt'):
	print "Copying skeleton grocery list since yours does not exist yet."
	line = os.popen('gnome-config --datadir').readline()
	shutil.copyfile(line[:-1]+'/grocget/list.txt',home+'/.grocget/list.txt')

item_file = open(home+'/.grocget/list.txt').readlines()

list_item = []
list_list = []
list_dic = {}

for line in item_file:
	list_item = line[3:-1]
	list_aisle = line[:3]
	list_list.append(list_item)
	list_dic[list_item]=list_aisle


list_list.sort()
total_items = len(list_list)

split=len(list_list)/4


for x in range(0,split):
	list_item = GtkListItem(list_list[x])
	list1.add(list_item)
	list_item.show()
for x in range(split,split*2):
	list_item = GtkListItem(list_list[x])
	list2.add(list_item)
	list_item.show()
for x in range(split*2,split*3):
	list_item = GtkListItem(list_list[x])
	list3.add(list_item)
	list_item.show()
for x in range(split*3,len(list_list)):
	list_item = GtkListItem(list_list[x])
	list4.add(list_item)
	list_item.show()


mainloop()
