"""
Q7Z: P7Zip GUI
Designed by Chris Giles

File:		Settings.py
Purpose:	Settings handler
"""


### Imports

# Q7Z 1
import	Import

# Python
try :
	import	os, platform, sys
except :
	Import.slException( "Python" )

# PyQt4
try :
	from	PyQt4	import QtCore, QtNetwork
except :
	Import.slException( "PyQt4" )

# Q7Z 2
import	Display, Main


### Variables

# Application
Application				= QtCore.QObject()
Application.sName		= "Q7Z"
Application.sVersion	= QtCore.QString( "0.7.1" )
Application.sDomain		= "k7z.sourceforge.net"
Application.sCurrent	= "/7Z/Q7Z/Current.txt"
Application.sDownload	= "http://sourceforge.net/project/showfiles.php?group_id=177755&package_id=204816"
QtCore.QCoreApplication.setApplicationName( Application.sName )

# Author
Author					= QtCore.QObject()
Author.sName			= "Chris Giles"
Author.Email			= QtCore.QObject()
Author.Email.sUser		= "Chris.G.27"
Author.Email.sDomain	= "@Gmail.com"
QtCore.QCoreApplication.setOrganizationName( Author.sName )
QtCore.QCoreApplication.setOrganizationDomain( Application.sDomain )

# Operating system
sOS					= platform.system()

# Path
Path				= QtCore.QObject()
Path.sUser			= os.getenv( 'HOME' )
Path.sKDE			= os.getenv( 'KDEDIR' )
Path.sKDE4			= ""
Path.sQ7Z			= ""
Path.sSep			= QtCore.QString( QtCore.QDir.separator() )
Path.Proxy			= QtNetwork.QNetworkProxy()

# Init
Init				= QtCore.QObject()
Init.bVerbose		= False
#Init.bInvisible		= False
Init.bAutoExit		= False
Init.bAutoUpdate	= True
"""
Init.Create				= QtCore.QObject()
Init.Extract				= QtCore.QObject()
Init.Extract.bBeneath = False
"""

# Timer
Timer						= QtCore.QObject()
Timer.Process				= QtCore.QObject()
Timer.Process.iPause		= 1000
Timer.Process.iWaitMax		= 50

# Commands
Command				= QtCore.QObject()

# Message
Message					= QtCore.QObject()
Message.sCreating		= "Creating ..."
Message.sExtracting		= "Extracting ..."
Message.sTesting		= "Testing ..."
Message.sChecking		= "Checking ..."
Message.sLaunching		= "Launching ..."
Message.Error			= QtCore.QObject()
Message.Error.Network	= "The updates server could not be contacted.<br>Check your network settings and try again."

# Input
Input				= QtCore.QObject()
Input.iNumArgs		= len(sys.argv)

"""
# Profiles
Profile				= QtCore.QObject()
Profile.iOther		= 1
Profile.iDefault	= 2
Profile.iStorage	= 3
"""

# Operations
Operation				= QtCore.QObject()
Operation.iClear		= 0
Operation.iCheck		= 1
Operation.iLaunch		= 2
Operation.iCreate		= 3
Operation.iExtract	= 4
Operation.iTest			= 5

# String-lists
List					= QtCore.QObject()
List.slFiles			= QtCore.QStringList()
List.slTHelpCmdArgs		= QtCore.QStringList()

# Setting
Settings					= QtCore.QSettings()
Setting						= QtCore.QObject()
Setting.Geometry			= QtCore.QObject()
Setting.Geometry.bPosition	= False
Setting.Appearance			= QtCore.QObject()
Setting.Appearance.bARC		= False
Setting.Exclusions		= QtCore.QObject()
Setting.Exclusions.sWildcards	= ".svn *Trash* *.sys"
#Setting.smCurrent			= QtGui.QSessionManager()

# Binaries
def slTestBinaries() :

	# Test command binary existences
	if QtCore.QString( os.popen( "which " + Command.s7z ).read() ).isEmpty() :
		Display.slNoBin( Command.s7z )
	if QtCore.QString( os.popen( "which " + Command.sTar ).read() ).isEmpty() :
		Display.slNoBin( Command.sTar )

# Linux
if sOS == "Linux" :

	# User
	if not Path.sUser :
		Path.sUser	= '/home/' + str(os.getenv( 'USER' )) + '/'

	# KDE
	if not Path.sKDE :
		Path.sKDE	= '/usr/'

	# Installation
	if QtCore.QFile.exists( Path.sKDE + "/share/apps/Q7Z/Source/" ) :
		Path.sQ7Z	= Path.sKDE + "/share/apps/Q7Z/"
	elif QtCore.QFile.exists( Path.sUser + "/.kde/share/apps/Q7Z/Source/" ) :
		Path.sQ7Z	= Path.sUser + "/.kde/share/apps/Q7Z/"
	else :
		Path.sQ7Z	= os.getcwd() + "/../"

	# Proxy
	sProxy = os.getenv( 'http_proxy' )
	if sProxy and sProxy != "" :

		sProxy = QtCore.QString( sProxy )

		# Type
		Path.Proxy.setType( QtNetwork.QNetworkProxy.HttpProxy )

		# Protocol supplied
		if sProxy.contains( "://" ) :
			sProxy = sProxy.section( "://" , 1 , 1 )

		# Username and password supplied
		if sProxy.contains( '@' ) :
			sLogin = sProxy.section( '@' , 0 , 0 )
			sProxy = sProxy.section( '@' , 1 , 1 )
			Path.Proxy.setUser( sLogin.section( ':' , 0 , 0 ) )
			Path.Proxy.setPassword( sLogin.section( ':' , 1 , 1 ) )

		# Port supplied
		if sProxy.contains( ':' ) :
			Path.Proxy.setHostName( sProxy.section( ':' , 0 , 0 ) )
			sPort = QtCore.QString( sProxy.section( ':' , 1 , 1 ) )
			Path.Proxy.setPort( int( sPort.section( '/' , 0 , 0 ) ) )
		else :
			Path.Proxy.setHostName( sProxy.section( '/' , 0 , 0 ) )
			Path.Proxy.setPort( int( 80 ) )

		# Temp
		#Path.Proxy.setApplicationProxy( Path.Proxy )

	# Commands
	Command.s7z		= "7z"
	Command.sTar	= "tar"
	#slTestBinaries()

# Windows
elif sOS == "Windows" :

	if not Path.sKDE :
		Path.sKDE	= ''

	if not Path.sUser :
		Path.sUser	= ''

	Path.sReg	= QtCore.QSettings( "HKEY_LOCAL_MACHINE\\Software\\Archiving\\Q7Z" , QtCore.QSettings.NativeFormat )
	Path.sQ7Z	= Path.sReg.value( "Path" ).toString()

	# Commands
	Path.sReg		= QtCore.QSettings( "HKEY_LOCAL_MACHINE\\Software\\7-Zip" , QtCore.QSettings.NativeFormat )
	Command.s7z		= Path.sReg.value( "Path" ).toString() + "/7z.exe"

# Others
else :

	print ""
	print "Unfortunately, your OS is not supported by " + Application.sName + " " + Application.sVersion + ".  Please email the author, specifying your system details."
	print ""

	sys.exit()


### Slots

# Init
def slInit() :

	# Visible?
	# TODO: Try to use the local 'bInvisible' instead
	if not Import.Init.bInvisible :

		# Window
		Settings.beginGroup( "Geometry" )
		#Main.mwMain.resize( Settings.value( "Size" ).toSize() )
		if Settings.contains( "Position" ) :
			Setting.Geometry.bPosition = True
			Main.mwMain.move( Settings.value( "Position" ).toPoint() )
		Settings.endGroup()

		# User service menus
		slUserServiceMenus( False )


# Load
def slLoad() :

	# Syntax
	Settings.beginGroup( "Syntax" )
	if Settings.contains( "Exclusions" ) :
		Setting.Exclusions.sWildcards = Settings.value( "Exclusions" ).toString()
	Settings.endGroup()

	# Visible?
	if not Import.Init.bInvisible :
		Main.uiSettings.leExclExt.setText( Setting.Exclusions.sWildcards )

	# Linux
	if sOS == "Linux" :

		# Verbose
		if Init.bVerbose is True :
			print "Settings.slLoad"
			print "Path.sUser = " + Path.sUser
			print ""

		# Visible?
		if not Import.Init.bInvisible :
			
			# Check Top Level
			if QtCore.QFile.exists( Path.sUser + "/.kde/share/apps/konqueror/servicemenus/Q7Z.marker.top" ) :
				Main.uiSettings.cbKTopLevel.setCheckState( QtCore.Qt.Checked )
			else :
				Main.uiSettings.cbKTopLevel.setCheckState( QtCore.Qt.Unchecked )

			# Enable
			Main.uiSettings.gbKonq.setEnabled( True )

# Save
def slSave() :

	#print "slSave"

	# Window
	Settings.beginGroup( "Geometry" )
	#Settings.setValue( "Size" , QtCore.QVariant(Main.mwMain.size()) )
	Settings.setValue( "Position" , QtCore.QVariant(Main.mwMain.pos()) )
	#Settings.remove( "Position" )
	Settings.endGroup()

# Settings accepted
def slAccept() :

	# Verbose
	if Init.bVerbose is True :
		print "Settings.slAccept"
		print "Path.sQ7Z = " + Path.sQ7Z
		print "Path.sUser = " + Path.sUser
		print ""

	# Syntax
	Setting.Exclusions.sWildcards = Main.uiSettings.leExclExt.displayText()
	Setting.Exclusions.sWildcards.remove( ',' )
	Setting.Exclusions.sWildcards.remove( ';' )
	Settings.beginGroup( "Syntax" )
	Settings.setValue( "Exclusions" , QtCore.QVariant(Setting.Exclusions.sWildcards) )
	Settings.endGroup()

	# Linux
	if sOS == "Linux" :

		# User service menus
		slUserServiceMenus( True )


# Dialog
def slDialog() :

	# Load
	slLoad()

	# Modal
	Main.dSettings.exec_()


# User service menus
def slUserServiceMenusSet( sDestPath ,  sFileExt ) :

	sBackupPath = Path.sQ7Z + "/Desktop/Context/"

	# Verbose
	if Init.bVerbose is True :
		print "sBackupPath = " + sBackupPath

	# Remove current entries
	os.popen( "rm -f " + Path.sUser + sDestPath + "Q7Z*" )

	# Create servicemenus directory
	dDestPath = QtCore.QDir( Path.sUser + sDestPath )
	if not dDestPath.exists() :
		dDestPath.mkpath( Path.sUser + sDestPath )

	# Copy
	QtCore.QFile.copy( sBackupPath + "Q7Zc.desktop" + sFileExt , Path.sUser + sDestPath + "Q7Zc.desktop" )
	QtCore.QFile.copy( sBackupPath + "Q7Ze.desktop" + sFileExt , Path.sUser + sDestPath + "Q7Ze.desktop" )
	QtCore.QFile.copy( sBackupPath + "Q7Z.marker" , Path.sUser + sDestPath + "Q7Z.marker" + sFileExt )


# User service menus
def slUserServiceMenus( bGUI ) :

	# KDE service menus
	sDestPath = "/.kde/share/apps/konqueror/servicemenus/"

	# Use GUI settings?
	if bGUI :

		# Top Level?
		if Main.uiSettings.cbKTopLevel.isChecked() :
			sFileExt = ".top"
		else :
			sFileExt = ""

		# Verbose
		if Init.bVerbose is True :
			print "Settings.slUserServiceMenus"
			print "sDestPath (KDE) = " + sDestPath

		slUserServiceMenusSet( sDestPath ,  sFileExt )

	# Top Level?
	if QtCore.QFile.exists( Path.sUser + sDestPath + "Q7Z.marker.top" ) :
		sFileExt = ".top"
	else :
		sFileExt = ""

	# KDE 4 service menus
	sDestPath = "/.kde4/share/kde4/services/ServiceMenus/"

	# Verbose
	if Init.bVerbose is True :
		print "sDestPath (KDE4) = " + sDestPath

	slUserServiceMenusSet( sDestPath ,  sFileExt )
