############################################################################
#    Copyright (C) 2005 by Manuel Amador (Rudd-O)                          #
#    rudd-o@amautacorp.com                                                 #
#                                                                          #
#    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 2 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, write to the                         #
#    Free Software Foundation, Inc.,                                       #
#    59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             #
############################################################################

# FIXME implement an interface that allows the indexer to compare in-store file objects' interface versions with its corresponding plugin"s interface version, to provide for automatic schema migration.  Bump the interface number on your plugin, and pof all files are automatically reindexed when they are modified (or perhaps upon startup/reload)
# FIXME implement an observer pattern so that the index database detects when the plugins are reloaded, suspend database access to client classes, run __prepare_indexes and refresh objects whose interfaces have changed (ay que pensar bien el orden de mierda de estas operaciones para que no se vaya todo a la verga"), 

import sys
import os
import glob
import imp

from MetadataService.common import utc_timestamp_to_local,convert_to_unicode,convert_from_unicode
import locale

# FIXME PRETTY PLEASE
# this may involve the creation of two other data types: naivedate (yy/mm/dd) and naivetime(hh:mm:ss) which operate in local time, and then client methods can interpret them and cast them to DateTime on their own, with this knowledge.
# or perhaps even better create an object daydelta = num of seconds after 0h00 and then we can sum that to the DateTime
# this should be moved to KDE's own module
import qt

def convert_qvariant(qvar,key=None):
	if qvar.type() == 3:
		# Guaranteed that the returned string is a string encoded in the platform's encoding
		return convert_qstring_to_string(qvar.toString())
	elif qvar.type() == 16:
		return qvar.toInt()
	elif qvar.type() == 18:
		return qvar.toBool()
	elif qvar.type() == 34:
		return qvar.toDouble()
	elif qvar.type() == 26:
		d = qvar.toDate()
		return DateTime.DateTime(d.year(),d.month(),d.day(),0,0,0) # QDate assumes local timezone
	elif qvar.type() == 27:
		return None # FIXME according to above instructions
	else:
		if key: key = " for key %s" % key
		raise ValueError, "QVariant unknown value " + str(qvar.type()) + key

def convert_qstring_to_string(qstring):
	""" Returns a regular string from a QString.  The returned string is encoded in the platform's preferred encoding """
	if not isinstance(qstring,qt.QString): raise ValueError
	return convert_from_unicode(unicode(qstring),locale.getpreferredencoding())

def convert_qstring_to_utf8(qstring):
	""" Returns a regular string from a QString.  The returned string is encoded in UTF-8  """
	if not isinstance(qstring,qt.QString): raise ValueError
	return convert_from_unicode(unicode(qstring),"UTF-8")

def convert_qstring_to_unicode(qstring):
	""" Returns a regular string from a QString.  The returned string is encoded in the platform's preferred encoding """
	if not isinstance(qstring,qt.QString): raise ValueError
	return unicode(qstring)


# this should make possible that plug-ins that need the KDE expert do not get imported
import kdecore
import kio
import threading
#from qt import QTimer
kdecore.KCmdLineArgs.init(["metadata-service"],"metadata-service","Metadata service","0.1",True)
k_app = kdecore.KApplication(False,False)
#k_timer = QTimer(None)
k_app_thread = threading.Thread(target=k_app.exec_loop)
k_app_thread.setDaemon(True)
k_app_thread.start()
#k_timer.start(200,False)

def get_mimetype(filename):
		""" Returns a file's MIME type. """
		f = convert_to_unicode(filename)
		kmimetype = kio.KMimeType.findByPath(f)
		mimetype = convert_qvariant(kmimetype.property("Name"))
		return mimetype

def get_metadata(filename):
		""" Returns a dictionary with the metadata keys and values for the file.  All strings are platform-encoded. """
		f = convert_to_unicode(filename)
		k = kio.KFileMetaInfo(f)
		returned = {}
		for groupname in k.groups():
			group = k.group(groupname)
			for keyname in group.keys():
				#try:
					kkeyname = "%s.%s" % (str(groupname),str(keyname))
					kkeyname = kkeyname.lower()
					value = convert_qvariant(k.value(keyname),keyname)
					returned[kkeyname] = value
				#except ValueError,e:
				#	print "WARNING: %s on key %s" % (str(e),keyname)
		return returned

def get_mounted_mountpoints(): #FIXME shouldn't this be converted to a plain list of strings before returning?????
	return [ convert_qstring_to_string(a.mountPoint()) for a in kdecore.KMountPoint.currentMountPoints(1) ]
