#!/usr/bin/env python
#####################################################################
#
#	Author : Kushal Das
#	Copyright (c)  2006 Kushal Das
#	kushal@fedoraproject.org
#	
#	Copyright: See COPYING file that comes with this distribution
#
#
#####################################################################
from Kphotobymail.kphotobymailUI import kphotobymailUI
from qt import *
from qttable import QTableItem
from Kphotobymail.config import config
from Kphotobymail.mail import kdMail
import cPickle as p
import sys
import os
import Kphotobymail.EXIF as EXIF
from kdecore import *
from kdeui import *
from Kphotobymail.kpbmSystemTray import kpbmSystemTray

class kdeApp:
	def __init__(self,parent):
		self.appname     = "Kphotobymail"
		self.description = "Kphotobymail is a PyKDE based flickr uploader tool"
		self.version     = "0.4.1"
		KCmdLineArgs.init (sys.argv, self.appname, self.description, self.version)
		self.app = KApplication ()
		self.app.connect(self.app,SIGNAL("lastWindowClosed()"),self.app,SLOT("quit()"))
		self.window = Kphotobymail(None,self)
		self.window.connect(self.window.systray, SIGNAL("quitSelected()"),self.app,SLOT("quit()"))
		self.app.setMainWidget(self.window)
		self.window.show()
		self.app.exec_loop()

class Kphotobymail(kphotobymailUI):
		""" The widget class
		"""
		def __init__(self,parent,qApp):
			kphotobymailUI.__init__(self,parent)
			#Check if configuration directory exists. If not, create it.
			self.configPrefix = os.path.join(os.path.expanduser('~'), ".kphotobymail")
			if not os.path.exists(self.configPrefix):
				os.mkdir(self.configPrefix)
				tempStr = 'cp /etc/kphotobymail.data ' + self.configPrefix
				os.popen(tempStr)
			self.stB = self.statusBar()
			self.progressBar=QProgressBar()
			self.stB.addWidget(self.progressBar,0,True)
			self.progressBar.setFixedHeight(12)
			self.qApp = qApp
			self.currentPath = os.path.expanduser('~')
			self.systray = kpbmSystemTray(self)
        		self.icon = "/usr/share/pixmaps/kphotobymail.png"
        		self.systray.setPixmap(QPixmap(UserIcon(self.icon)))
       			self.systray.setAcceptDrops(True)
			self.systray.show()
			self.systray.setCaption('KPhotobymail')
			self.aboutdata = KAboutData('Kphotobymail','Kphotobymail','0.4.1','Kphotobymail is a PyQt based flickr uploader tool',1,'(c) 2006 Kushal Das','','http://kphotobymail.sourceforge.net/')
			self.aboutdata.addAuthor('Kushal Das','','kushal@fedoraproject.org','http://kushaldas.blogspot.com')
			self.aboutdata.setProgramLogo(QImage(self.icon))
			self.abt = KAboutApplication(self.aboutdata,self)
			self.connect(self.systray, PYSIGNAL("testSignal"), self.gotIt )
			
		def select(self):
			""" It opens a select Box & selects the files
			"""
			self.fileDialog = QFileDialog(self.currentPath)
			self.fileDialog.setDir(self.currentPath)
			names = self.fileDialog.getOpenFileNames("Images (*.png *.jpg *.JPG)",'',self,"Select pics","Select Pics")
			self.currentPath = str(self.fileDialog.dirPath())
			self.fileDialog = None
			for name in names:
				self.insertFile(name)

		def upload(self):
			"""It will create a kdMail object & passes the configuration info along
			with the file names,tiles,descriptions.
			"""
			self.fileTable.setReadOnly(True)
			f = file(self.configPrefix+'/kphotobymail.data')
			data = p.load(f)
			filenumbers = self.fileTable.numRows()
			if filenumbers == 0:
				self.message("Select File(s) first")
				return
			self.uploadBttn.setEnabled(0)
			self.files = []
			for i in range(0,filenumbers):
				entry = []
				entry.append( str(self.fileTable.text(i,0)))
				entry.append( str(self.fileTable.text(i,1)))
				entry.append( str(self.fileTable.text(i,2)))
				self.files.append(entry)
			self.fileTable.setReadOnly(False)
			km = kdMail(self.files,data,self)
			km.start()
				
		def picChange(self):
			""" To change the pictures as the user clicks different rows
			"""
			i = self.fileTable.currentRow()
			self.tagClear()
			if i != -1: 
				qm = QImage(self.fileTable.text(i,0))
				qm = qm.scale(250,190,QImage.ScaleMin)
				qx = QPixmap(qm)
				self.picLabel.setFixedSize(qx.size())
				self.picLabel.setPixmap(qx)
				self.getExif(self.fileTable.text(i,0))
		
		def rowDel(self):
			""" When user double clicks it will delete a row
			"""
			i = self.fileTable.currentRow()
			self.fileTable.removeRow(i)
			self.picLabel.setFixedSize(QSize(250,190))
			self.picLabel.setPixmap(self.image0)
			self.tagClear()
			
		def config(self):
			"""Open configuration dialog
			"""
			self.con = config(self)
			self.con.show()

		def about(self):
			"""Open about dialog
			"""
			self.abt.show()
		
		def clearAll(self):
			"""Clear all Selected files"""
			for i in range(0,self.fileTable.numRows()):
				self.fileTable.removeRow(0)
			self.progressBar.reset()
			self.picLabel.setFixedSize(QSize(250,190))
			self.picLabel.setPixmap(self.image0)
			self.tagClear()
				
		def message(self,mes):
			"""Show error message"""
			self.stB.message(mes,5000)
		
		def progress(self,pro):
			"""Update the progressBar"""
			self.progressBar.setProgress(pro)
			
		def getExif(self,file):
			"""Get EXIF data"""
			try:
				f = open(str(file),'rb')
				tags = EXIF.process_file(f)
				f.close()
				self.makeLabel.setText(str(tags['Image Make']))
				self.modelLabel.setText(str(tags['Image Model']))
				self.xresLabel.setText(str(tags['Image XResolution']))
				self.yresLabel.setText(str(tags['Image YResolution']))
				self.orientationLabel.setText(str(tags['Image Orientation']))
				self.datetimeLabel.setText(str(tags['Image DateTime']))
				self.isoLabel.setText(str(tags['EXIF ISOSpeedRatings']))
				self.exposuretimeLabel.setText(str(tags['EXIF ExposureTime'])+' sec.')
				temp = str(tags['EXIF FNumber'])
				tempAt = temp.find('/')
				num1 = float(temp[:tempAt])
				num2 = float(temp[tempAt+1:])
				s = "%.1f" % (num1/num2)
				self.fnumberLabel.setText('f/'+s)
				self.maxapertureLabel.setText(str(tags['EXIF MaxApertureValue']))
				temp = str(tags['EXIF FocalLength'])
				tempAt = temp.find('/')
				num1 = float(temp[:tempAt])
				num2 = float(temp[tempAt+1:])
				s = "%.1f" % (num1/num2)
				self.focallengthLabel.setText(s+' mm.')
			except:
				print "No problem"
				

		def tagClear(self):
			"""Clear all labels for EXIF data"""
			self.makeLabel.setText('')
			self.modelLabel.setText('')
			self.xresLabel.setText('')
			self.yresLabel.setText('')
			self.orientationLabel.setText('')
			self.datetimeLabel.setText('')
			self.isoLabel.setText('')
			self.exposuretimeLabel.setText('')
			self.fnumberLabel.setText('')
			self.maxapertureLabel.setText('')
			self.focallengthLabel.setText('')
			
		def gotIt(self, file):
			'''slot for SystemTray'''
			self.insertFile(file[7:])
			
		def insertFile(self, name):
			'''Add file to the table'''
			i = self.fileTable.numRows()
			self.fileTable.insertRows(i)
			self.fileTable.setItem(i,0,QTableItem(self.fileTable,QTableItem.Never,name))

		

if __name__=="__main__":
#Check if any other instance is there or not
	tmp = os.popen('ps -e | grep kphotobymail').readlines()
	if (len(tmp) < 2):
		kApp=kdeApp(sys.argv)


