#
#    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 3 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, see <http://www.gnu.org/licenses/>.
#

import re
import os,subprocess,tempfile
from PySide import QtGui, QtCore

# Calling the normal rendering
PageFile = open(App.activeDocument().PovProject.PageResult,'rb')
fd, TempFile = tempfile.mkstemp(suffix='.pov')
f = open(TempFile,'wb')
f.write(PageFile.read())
f.close()
os.close(fd)

# Replace textures
replace = { "<1,0,1>" : "texture{ Cherry_Wood }", 
            "<1,1,0.5>":"texture{ Cork }",
            "<1,0,1>":"texture{ DMFDarkOak }",
            "<0,1,0>":"texture{ DMFLightOak }",
            "<0,0.33,0>":"texture{ DMFWood1 }",
            "<0.67\d*,0.67\d*,0>":"texture{ DMFWood2 }",
            "<0.33\d*,0,0>":"texture{ DMFWood3 }",
            "<1,0.67\d*,1>":"texture{ DMFWood4 }",
            "<0,0,1>":"texture{ Dark_Wood }",
            "<0.67\d*,0.33\d*,1>":"texture{ Chrome_Metal }",
            "<0.67\d*,0,0.5>":"texture{ Brass_Metal }" }

withintexture = 0
textureblock = ""
newtexture = ""

output = ""

f = open(TempFile,'r')
line = f.readline()
while line:
    if (line.strip().startswith("texture {")):
        withintexture = 1
        textureblock = ""
        newtexture = ""

    if (withintexture == 1):
        textureblock += line

        for key in replace.keys():
            #if (line.find(key)>0):
            if (len(re.findall(key, line)) > 0):
                newtexture = replace[key]

        if (line.strip().startswith("}")):
            withintexture = 0
            if (newtexture != ""):
                output+=newtexture
            else:
                output+=textureblock
    else:
        output+=line

    line = f.readline()

f.close()

f = open(TempFile,'w')
f.write(output)
f.close()

filters = ('Portable Network Graphics (*.png)')
dialog = QtGui.QFileDialog
fileName, _ = dialog.getSaveFileName(None, 'Save Rendering', dir=tempfile.gettempdir(), filter=filters, selectedFilter='Portable Network Graphics (*.png)')

if fileName:
	# user clicked OK
	execcommand = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Raytracing").GetString("PovrayExecutable") + " "+FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Raytracing").GetString("OutputParameters")+" +W"+str(FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Raytracing").GetInt("OutputWidth"))+" +H"+str(FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Raytracing").GetInt("OutputHeight"))+" +O"+fileName+" "
	print(execcommand+TempFile)
	subprocess.call(execcommand+TempFile,shell=True)
	import ImageGui
	ImageGui.open(fileName)

#del TempFile,PageFile