"""
     qtgui/TextLabel.py: CCP4MG Molecular Graphics Program
     Copyright (C) 2001-2008 University of York, CCLRC
     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 math
from global_definitions import GLWIDGETS
import cprim
import sys

def getLatexInput(text,fontsize):
  texHeader = """\\documentclass[a4paper,11pt,landscape]{article}
\\nonstopmode
\\usepackage{amsmath}
\\usepackage{color}
\\usepackage{anyfontsize}
\\pagestyle{empty}

\\begin{document}
{\n"""

  texFooter = """
}
\end{document}\n"""

  s = texHeader
  s += "\\fontsize{"+str(fontsize)+"}{"+str(fontsize*1.2)+"}\\selectfont\n"
  s += text
  s += texFooter
  return s

def renderLatexToPixmap(text,fontsize=11):
  import os
  import tempfile
  import subprocess
  import shutil
  texinp = getLatexInput(text,fontsize)
  tdir = tempfile.mkdtemp()
  cwd = os.getcwd()
  os.chdir(tdir)
  
  f = open("temp.tex","w")
  f.write(texinp)
  f.close()
  
  try:
    retcode = subprocess.call(["pdflatex","temp.tex"])
  except:
    retcode = -1
  if retcode != 0:
    print "Error running pdflatex"
    raise Exception("Error running pdflatex")
  
  try:
    retcode = subprocess.call(["pdfcrop","temp.pdf"])
  except:
    retcode = -1
  if retcode != 0:
    print "Error running pdfcrop"
    raise Exception("Error running pdfcrop")
  
  try:
    retcode = subprocess.call(["convert","-density","100","temp-crop.pdf","template-crop.png"])
  except:
    retcode = -1
  if retcode != 0:
    print "Error running convert"
    raise Exception("Error running convert")
  
  try:
    retcode = subprocess.call(["blacktowhite","template-crop.png","template-crop-white.png"])
  except:
    retcode = -1
  if retcode != 0:
    print "Error running blacktowhite"
    raise Exception("Error running blacktowhite")
  
  pix_b = QtGui.QImage("template-crop.png")
  pix_w = QtGui.QImage("template-crop-white.png")
  required_width,required_height = pix_w.width(),pix_w.height()
  text_width = required_width;
  text_height =  required_height
  required_width,required_height = max(required_width,8),max(required_height,8)
  required_width,required_height = 2<<int(math.ceil(math.log(required_width)/math.log(2))-1), 2<<int(math.ceil(math.log(required_height)/math.log(2))-1)

  pixmap_w = QtGui.QImage(required_width,required_height,QtGui.QImage.Format_ARGB32)
  pixmap_b = QtGui.QImage(required_width,required_height,QtGui.QImage.Format_ARGB32)
  pixmap_w.fill(0)
  pixmap_b.fill(0)
  painter = QtGui.QPainter()
  painter.begin(pixmap_w)
  painter.drawImage(0,pixmap_w.height()-pix_w.height()-1,pix_w)
  painter.end()
  painter.begin(pixmap_b)
  painter.drawImage(0,pixmap_b.height()-pix_b.height()-1,pix_b)
  painter.end()

  os.chdir(cwd)

  shutil.rmtree(tdir)
  return ((pixmap_w,pixmap_b),(text_width,text_height))

def renderStringToPixmap(strings,font=None):
  flip_labels = False
  if QtGui.QApplication.instance().property("flip_labels").toPyObject()!=None:
    flip_labels= QtGui.QApplication.instance().property("flip_labels").toPyObject()
  if not font: font = QtGui.QFont("Times",16)
  import FontedPositionedStrings
  fontedPositionedStrings = FontedPositionedStrings.FontedPositionedStringsFromText(unicode(strings+'  '),font)
  rect =  fontedPositionedStrings.getBoundingRect()
  descent =  fontedPositionedStrings.getDescent()
  required_width,required_height = rect.width(),rect.height()
  text_width = required_width;
  text_height =  required_height
  required_width,required_height = max(required_width,8),max(required_height,8)
  required_width,required_height = 2<<int(math.ceil(math.log(required_width)/math.log(2))-1), 2<<int(math.ceil(math.log(required_height)/math.log(2))-1)

  #pixmap_w = QtGui.QPixmap(required_width,required_height)
  pixmap_w = QtGui.QImage(required_width,required_height,QtGui.QImage.Format_ARGB32)
  pixmap_w.fill(0)
  painter = QtGui.QPainter()
  painter.begin(pixmap_w)
  painter.setPen(QtGui.QColor(255,255,255,255))
  if flip_labels:
    FontedPositionedStrings.drawFontedPositionedStrings(fontedPositionedStrings.getStrings(),painter,-rect.left(),rect.height()-descent-1,font)
  else:
    FontedPositionedStrings.drawFontedPositionedStrings(fontedPositionedStrings.getStrings(),painter,-rect.left(),required_height-descent-1,font)
  painter.end()
  #pixmap_b = QtGui.QPixmap(required_width,required_height)
  pixmap_b = QtGui.QImage(required_width,required_height,QtGui.QImage.Format_ARGB32)
  pixmap_b.fill(0)
  painter = QtGui.QPainter()
  painter.begin(pixmap_b)
  painter.setPen(QtGui.QColor(0,0,0,255))
  if flip_labels:
    FontedPositionedStrings.drawFontedPositionedStrings(fontedPositionedStrings.getStrings(),painter,-rect.left(),rect.height()-descent-1,font)
  else:
    FontedPositionedStrings.drawFontedPositionedStrings(fontedPositionedStrings.getStrings(),painter,-rect.left(),required_height-descent-1,font)
  painter.end()
  if flip_labels:
    #pixmap_w = QtGui.QPixmap.fromImage(pixmap_w.toImage().mirrored(False,True))
    #pixmap_b = QtGui.QPixmap.fromImage(pixmap_b.toImage().mirrored(False,True))
    pixmap_w = pixmap_w.mirrored(False,True)
    pixmap_b = pixmap_b.mirrored(False,True)

  return ((pixmap_w,pixmap_b),(text_width,text_height))

def CreateTextures(text,font=None):
    if not font: font = QtGui.QFont("Times",16)
    import opengl
    pixmaps,twandh = renderStringToPixmap(text,font)

    import FontedPositionedStrings
    fontedPositionedStrings = FontedPositionedStrings.FontedPositionedStringsFromText(unicode(text+'  '),font)
    strings = fontedPositionedStrings.getStrings()
    fnSize = font.pointSize()
    theText = ''
    fnSize = 12
    for s in strings:
      theText += s['text']
      if s.has_key('font') and s['font'].has_key('size') and s['text'].strip():
        fnSize = int(s['font']['size'])

    theText = theText.strip()
    if theText.startswith('$latex') and theText.endswith('$latex') and len(theText)>12:
        try:
          pixmaps_new,twandh_new = renderLatexToPixmap(theText[6:-6],fnSize)
          pixmaps,twandh = pixmaps_new,twandh_new
        except:
          pass

    glWidget = GLWIDGETS()[0]
    glWidget.makeCurrent()
    opengl.glPixelStorei(opengl.GL_UNPACK_ALIGNMENT, 1)
    opengl.glEnable(opengl.GL_TEXTURE_2D)
    opengl.glTexParameteri(opengl.GL_TEXTURE_2D, opengl.GL_TEXTURE_WRAP_S, opengl.GL_CLAMP);
    opengl.glTexParameteri(opengl.GL_TEXTURE_2D, opengl.GL_TEXTURE_WRAP_T, opengl.GL_CLAMP);
    opengl.glTexParameteri(opengl.GL_TEXTURE_2D, opengl.GL_TEXTURE_MAG_FILTER, opengl.GL_LINEAR);
    opengl.glTexParameteri(opengl.GL_TEXTURE_2D, opengl.GL_TEXTURE_MIN_FILTER, opengl.GL_LINEAR);
    tex_ids = (glWidget.bindTexture(pixmaps[0],format = opengl.GL_RGBA),glWidget.bindTexture(pixmaps[1],format = opengl.GL_RGBA))
    return tex_ids,pixmaps,twandh

def CreateTextLabel(text,cart1,cart2,font=None):
    if font and type(font)==dict:
		qfont = QtGui.QFont(font["family"],int(font["size"]))
		if font["underline"]:
			qfont.setUnderline(True)
		else:
			qfont.setUnderline(False)
		if font["weight"] == "bold":
			qfont.setBold(True)
		else:
			qfont.setBold(False)
		if font["slant"] == "i" or font["slant"] == "o":
			qfont.setItalic(True)
		else:
			qfont.setItalic(False)
		font = qfont

    if not font: font = QtGui.QFont("Times",16)
    tex_ids,pixmaps,twandh = CreateTextures(text,font)
    label_ob = cprim.Text(cart1,tex_ids[0],tex_ids[1],pixmaps[0].width(),pixmaps[0].height(),cart2,str(text))
    label_ob.SetTextWidth(twandh[0])
    label_ob.SetTextHeight(twandh[1])
    fm = QtGui.QFontMetrics(font)
    sys.stdout.flush()
    label_ob.SetFontDescent(fm.descent())
    if font.italic():
    	label_ob.SetFontSlant("i")
    label_ob.SetFontUnderline(font.underline())
    label_ob.SetFontStrikeout(font.strikeOut())
    label_ob.SetFontFamily(str(font.family().toUtf8()))
    label_ob.SetFontSize(font.pointSize())
    if font.bold():
      label_ob.SetFontWeight("bold")
    if font.italic():
      label_ob.SetFontSlant("i")
    return label_ob

def CreateBillBoardTextLabel(text,cart1,cart2,font=None):
    if sys.argv.count('-quit')>0:
    	label_ob = cprim.BillBoardText(cart1,str(text),cart1)
    	return label_ob
    tex_ids,pixmaps,twandh = CreateTextures(text,font)
    label_ob = cprim.BillBoardText(cart1,tex_ids[0],tex_ids[1],pixmaps[0].width(),pixmaps[0].height(),cart2,str(text))
    label_ob.SetTextWidth(twandh[0])
    label_ob.SetTextHeight(twandh[1])
    return label_ob
