"""
Technical information
"""
"""
     qtgui/plugins/TechnicalInfo.py: CCP4MG Molecular Graphics Program
     Copyright (C) 2009-2010 University of York
     Copyright (C) 2012 STFC

     This library is free software: you can redistribute it and/or
     modify it under the terms of the GNU Lesser General Public License
     version 3, modified in accordance with the provisions of the 
     license to address the requirements of UK law.
 
     You should have received a copy of the modified GNU Lesser General 
     Public License along with this library.  If not, copies may be 
     downloaded from http://www.ccp4.ac.uk/ccp4license.php
 
     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 Lesser General Public License for more details.
"""
from PyQt4 import QtCore, QtGui
import MGSimpleDialog
import MGApplication
import sys,os

def handleTechDialog(checked=False):
  mainwin = MGApplication.GetMainWindow()
  if not hasattr(mainwin,"tech_dialog"):
    mainwin.tech_dialog = AboutTech(mainwin)
  mainwin.tech_dialog.UnClose()
  

def initializePlugin():
  mainwin = MGApplication.GetMainWindow()
  if not sys.argv.count('-quit'):
    menu_defn = {}
    menu_defn['icon'] = 'technicalinfo'
    menu_defn['icon_path'] = os.path.normpath(os.path.dirname(__file__))
    menu_defn['text'] = "Technical information"
    menu_defn["tip"] = "Technical information"
    window_item = mainwin.addMenuDefinition(menu_defn['text'],menu_defn,'Tools',draw_menu=False)
    window_item.triggered.connect(handleTechDialog)

def getBuildInfo():
	text = ""
	if os.path.exists(os.path.join(os.environ["CCP4MG"],"lib","TIMESTAMP")):
		try:
			f = open(os.path.join(os.environ["CCP4MG"],"lib","TIMESTAMP"))
			lines = f.readlines()
			for l in lines:
				text += l + "<br>"
		except:
			text = "Unknown"
        return text

def getProcessorNameFromRegistry():
	try:
		import _winreg
		reg = _winreg.ConnectRegistry(None,_winreg.HKEY_LOCAL_MACHINE)
		key = _winreg.OpenKey(reg,"HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0")
		for i in range(1024):                                           
			try:
				name,value,type = _winreg.EnumValue(key,i)
				if name == "ProcessorNameString":
					return value
			except:
				pass
		_winreg.CloseKey(key)
		_winreg.CloseKey(reg)
	except:
		return ""

	return ""

def getSystemInfo():
	import platform
	system = platform.system()
	text = "Platform: "+platform.platform()+"<br>\n"
	if sys.platform == "darwin":
		text += "Processor: "+platform.processor()+"<br>\n"
		text += "OS X version: " + platform.mac_ver()[0]+"<br>\n"
		try:
			import subprocess
			hardinfo = subprocess.Popen(["system_profiler","SPHardwareDataType","-detailLevel","mini"], stdout=subprocess.PIPE).communicate()[0]
			dispinfo = subprocess.Popen(["system_profiler","SPDisplaysDataType","-detailLevel","mini"], stdout=subprocess.PIPE).communicate()[0]
		except:
			hardinfo = ""
			dispinfo = ""
		if hardinfo.find('Processor Name')>-1 and len(hardinfo[hardinfo.find('Processor Name'):])>16 and hardinfo[hardinfo.find('Processor Name')+16:].find('\n') > -1:
			model = hardinfo[hardinfo.find('Processor Name')+16:]
			model = model[:model.find('\n')].strip()
			speed = ''
			if hardinfo.find('Processor Speed')>-1 and len(hardinfo[hardinfo.find('Processor Speed'):])>17 and hardinfo[hardinfo.find('Processor Speed')+17:].find('\n') > -1:
				speed = hardinfo[hardinfo.find('Processor Speed')+17:]
				speed = speed[:speed.find('\n')].strip()
			nproc = 0
			if hardinfo.find('Total Number Of Cores')>-1 and len(hardinfo[hardinfo.find('Total Number Of Cores'):])>len('Total Number Of Cores') and hardinfo[hardinfo.find('Total Number Of Cores')+len('Total Number Of Cores'):].find('\n') > -1:
				nproc = hardinfo[hardinfo.find('Total Number Of Cores')+len('Total Number Of Cores')+1:]
				nproc = nproc[:nproc.find('\n')].strip()
			if len(model)>0:
				text += "Processor details: "+model
				if speed: text += " "+speed
				if nproc>0:
					text+= ' ('+str(nproc)+' cores available)'
				text += "<br>\n"
		text += """
<span> Further information:
<span id="opensystem_profile"><a href="javascript:switchDiv('system_profile','system_profile','opensystem_profile');">
(+)</a>
</span>
<span id="system_profile" style="position:absolute;display:none;"><br>
		"""
		text += hardinfo.replace('\n','<br>').replace('        ','&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;')
		text += dispinfo.replace('\n','<br>').replace('        ','&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;')
		text += """
<a href="javascript:clickedMinus('system_profile','system_profile','opensystem_profile');">(close)</a></span>
</span>
        	"""

	elif sys.platform == "linux2":
		text += "Processor: "+platform.processor()+"<br>\n"
		if hasattr(platform,"linux_distribution"):
			text += "Linux distribution: " + platform.linux_distribution()[0]+" "+ platform.linux_distribution()[1]+" "+ platform.linux_distribution()[2]+"<br>\n"
		elif hasattr(platform,"dist"):
			text += "Linux distribution: " + platform.dist()[0]+" "+ platform.dist()[1]+" "+ platform.dist()[2]+"<br>"
		try:
			import subprocess
			cpuinfo = subprocess.Popen(["cat","/proc/cpuinfo"], stdout=subprocess.PIPE).communicate()[0]
			meminfo = subprocess.Popen(["cat","/proc/meminfo"], stdout=subprocess.PIPE).communicate()[0]
		except:
			cpuinfo = ''
			meminfo = ''
		if cpuinfo.find('model name')>-1 and len(cpuinfo[cpuinfo.find('model name'):])>12 and cpuinfo[cpuinfo.find('model name')+12:].find('\n') > -1:
			model = cpuinfo[cpuinfo.find('model name')+12:]
			model = model[:model.find('\n')].strip()
			nproc = cpuinfo.count('\nmodel name\t')
			if len(model)>0:
				text += "Processor details: "+model
				if nproc>0:
					text+= ' ('+str(nproc)+' processors available)'
				text += "<br>\n"
		text += """
<span> Further information:
<span id="openprocinfo"><a href="javascript:switchDiv('procinfo','procinfo','openprocinfo');">
(+)</a>
</span>
<span id="procinfo" style="position:absolute;display:none;"><br>
		"""
		text += cpuinfo.replace('\n','<br>\n')
		text += meminfo.replace('\n','<br>\n')
		text += """
<a href="javascript:clickedMinus('procinfo','procinfo','openprocinfo');">(close)</a></span>
</span>
		"""
	elif sys.platform == "win32":
		text += "Processor Name: "+getProcessorNameFromRegistry()
		if os.environ.has_key("NUMBER_OF_PROCESSORS"):
			text+= " ("+os.environ["NUMBER_OF_PROCESSORS"]+" processors available)"
		text += "<br>\n"
		text += "Processor details: "+platform.processor()+"<br>\n"
		text += "Windows version: " + platform.win32_ver()[0]+" "+ platform.win32_ver()[1]+" "+ platform.win32_ver()[2]+"<br>\n"
	else:
		text += "Processor: "+platform.processor()+"<br>\n"

	return text

def getOtherInfo():
	text = ''
	text += "Qt version: "+QtCore.QT_VERSION_STR+"<br>\n"
	text += "PyQt4 version: "+QtCore.PYQT_VERSION_STR+"<br>\n"
	text += "Python version: "+sys.version+"<br>\n"
	return text

def getGLInfo():
	text = ""
	mainwin = MGApplication.GetMainWindow()
	try:
		import glShaders
        	shaderVersion = glShaders.MGGLShader.getShadingLanguageVersion()
	except:
        	shaderVersion = "OpenGL shaders not available"
	if hasattr(mainwin,"glWidget") and mainwin.glWidget.isValid():
		mainwin.glWidget.makeCurrent()
		import opengl
		text += "Direct rendering: "+str(mainwin.glWidget.context().format().directRendering())+"<br>"
		text += "GL vendor: "+opengl.glGetString(opengl.GL_VENDOR)+"<br>"
		text += "GL renderer: "+opengl.glGetString(opengl.GL_RENDERER)+"<br>"
		text += "GL version: "+opengl.glGetString(opengl.GL_VERSION)+"<br>"
		text += "GL shader version: "+shaderVersion+"<br>"
		text += "<span>GL extensions: "
		text += """
<span id="openglext"><a href="javascript:switchDiv('glext','glext','openglext');">
(+)</a>
</span>
<span id="glext" style="position:absolute;display:none;"><br>
		"""
		text += opengl.glGetString(opengl.GL_EXTENSIONS)
		text += """
<a href="javascript:clickedMinus('glext','glext','openglext');">(close)</a></span>
</span>
		"""
        return text

class AboutTech(MGSimpleDialog.MGSimpleDialog):

    def UnClose(self):
        label_text = self.getLabelText()
        self.label.setHtml(label_text)
        MGSimpleDialog.MGSimpleDialog.UnClose(self)


    def getLabelText (self):
	label_text = """<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
 <title>CCP4MG Technical Information</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script type="text/javascript">
function jsrsArrayFromString(s, delim){ 
 var d = (delim==null)? '~' : delim; 
 return s.split(d); 
}
function changeObjectPosition(objectId, newPosition) {
    // first get the object's stylesheet
    var styleObject = getStyleObject(objectId);

    // then if we find a stylesheet, set its position
    // as requested
    //
    if (styleObject) {
	styleObject.position = newPosition;
	return true;
    } else {
	return false;
    }
}

function changeObjectDisplay(objectId, newDisplay) {
    // first get the object's stylesheet
    var styleObject = getStyleObject(objectId);

    // then if we find a stylesheet, set its display
    // as requested
    //
    if (styleObject) {
	styleObject.display = newDisplay;
	return true;
    } else {
	return false;
    }
}

function getStyleObject(objectId) {
  // checkW3C DOM, then MSIE 4, then NN 4.
  if(document.getElementById && document.getElementById(objectId)) {
	return document.getElementById(objectId).style;
   }
   else if (document.all && document.all(objectId)) {  
	return document.all(objectId).style;
   } 
   else if (document.layers && document.layers[objectId]) { 
	return document.layers[objectId];
   } else {
	return false;
   }
}

function hideAll(all_div_ids_str)
{
  all_div_ids = jsrsArrayFromString(all_div_ids_str,'~');
  for(i=0;i<all_div_ids.length;i++){
    changeObjectPosition(all_div_ids[i],"absolute");
    changeObjectDisplay(all_div_ids[i],"none");
  }
}

function clickedMinus(div_id,all_div_ids_str,opener_id){
  var style_sheet = getStyleObject(div_id);
  if (style_sheet)
  {
    hideAll(all_div_ids_str);
    document.getElementById(opener_id).innerHTML = "<a href=\\"javascript:switchDiv('"+div_id+"','"+all_div_ids_str+"','"+opener_id+"');\\">(+)<\/a>";
  }
}

function switchDiv(div_id,all_div_ids_str,opener_id){
  var style_sheet = getStyleObject(div_id);
  if (style_sheet)
  {
    hideAll(all_div_ids_str);
    changeObjectDisplay(div_id, "block");
    changeObjectPosition(div_id, "relative");
    document.getElementById(opener_id).innerHTML ="<a href=\\"javascript:clickedMinus('"+div_id+"','"+all_div_ids_str+"','"+opener_id+"');\\">(-)<\/a>"; 
  }
  else 
  {
    alert("Problem switching object visibility.");
  }
}
</script>
</head>
<body>
	"""

        label_text += "<ul>"

	label_text += '<li><b><span style="font-family:sans;">CCP4MG Build Information:</span></b><br>'
        gl_text = getBuildInfo()
        label_text += '<span style="font-family:sans;">'+gl_text+'</span>'

	label_text += '<li><b><span style="font-family:sans;">System Information:</span></b><br>'
        gl_text = getSystemInfo()
        label_text += '<span style="font-family:sans;">'+gl_text+'</span>'

	label_text += '<li><b><span style="font-family:sans;">OpenGL Information:</span></b><br>'
        gl_text = getGLInfo()
        label_text += '<span style="font-family:sans;">'+gl_text+'</span>'

	label_text += '<li><b><span style="font-family:sans;">Other Information:</span></b><br>'
        gl_text = getOtherInfo()
        label_text += '<span style="font-family:sans;">'+gl_text+'</span>'
        label_text += "</ul>"
	label_text += "</body>"
	label_text += "</html>"
        return label_text

    def __init__(self,parent=None):
        MGSimpleDialog.MGSimpleDialog.__init__(self,parent)
        self.setWindowTitle(self.tr("Technical Information"))
        layout = QtGui.QVBoxLayout(self)
        from PyQt4 import QtWebKit
        self.label = QtWebKit.QWebView()
        layout.addWidget(self.label)
        self.setLayout(layout)
        self.setSizeGripEnabled(0)
        self.menu_defn['icon'] = 'technicalinfo'
        self.menu_defn['icon_path'] = os.path.normpath(os.path.dirname(__file__))
        #self.CreateMenuEntry()

if __name__ == "__main__":
	if "-quit" in sys.argv:
		sys.exit()
	print getBuildInfo()
	print getSystemInfo()
	print getGLInfo()
	print getProcessorNameFromRegistry()
