#STL_STEP_ContactSheetv0.FCMacro
#FreeCAD 0.17 and FreeCAD 0.18 with ImageMagick V6
#May not work with some versions of Windoze

import FreeCAD
import Mesh
import os
import subprocess
from PySide import QtGui, QtCore

#home = os.getenv("HOME")

MdlBaseDir = os.getcwd() #Just something to put in the dialog to start with


# UI Class definitions

class ExampleModalGuiClass(QtGui.QDialog):
	
	def __init__(self):
		super(ExampleModalGuiClass, self).__init__()
		self.initUI()
	def initUI(self):
		self.SubDirSweep = 0
		# create the window
		# define window		xLoc,yLoc,xDim,yDim
		self.setGeometry(	250, 250, 600, 150)
		self.setWindowTitle("STL and STEP Processor")
		#self.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)

		# create some Labels
		self.InDirlabelHeader = QtGui.QLabel("Target Directory: ", self)
		self.InDirlabelHeader.move(40, 10)

		#Label with the current trarget directory
		self.InDirlabel = QtGui.QLabel(MdlBaseDir, self)
		self.InDirlabel.setFixedWidth(580)
		self.InDirlabel.move(40, 30)

		self.inDirButton = QtGui.QPushButton('Change Target Directory', self)
		self.inDirButton.clicked.connect(self.FindDir)
		self.inDirButton.move(140, 55)

		# Directory Sweep checkbox
		self.DirSweepchkbx = QtGui.QCheckBox("Include Subdirectories?", self)
		self.DirSweepchkbx.move(140,85)
		self.DirSweepchkbx.toggle()
		self.DirSweepchkbx.setChecked(False)
		self.DirSweepchkbx.stateChanged.connect(self.YepInclude)


		# cancel button
		self.QuitButton = QtGui.QPushButton('Quit', self)
		self.QuitButton.clicked.connect(self.QuitNow)
		self.QuitButton.move(300, 120)
		# OK button
		self.GoButton = QtGui.QPushButton('Go', self)
		self.GoButton.clicked.connect(self.ProcessDir)
		self.GoButton.move(140, 120)
		# now make the window visible
		self.show()
	
	

	def ProcessDir(self):
		#Gather the filenames of all files present
		STLFiles=[]
		STLPath = []
		#print(Fullflist)
		MdlBaseDir = os.getcwd()
		print(MdlBaseDir)
		#Create Model file list with only STL and STEP files

		#This is if the sweep through subdirectory check box is ticked
		if self.SubDirSweep==1:
			print("Hello")
			for folderName, subfolders, filenames in os.walk(MdlBaseDir):
				for filename in filenames:
					if filename.rsplit(".",1)[1].lower()=="stl" or filename.rsplit(".",1)[1].lower()=="step":
						STLFiles.append(filename)
						STLPath.append(os.path.join(folderName,filename))
						print("found "+filename)
        
		else:
			print("Nope")
			Fullflist = os.listdir(os.getcwd())
			for item in Fullflist:
				try:
					if item.rsplit(".",1)[1].lower()=="stl" or item.rsplit(".",1)[1].lower()=="step":
						STLFiles.append(item)
						STLPath.append(os.path.join(MdlBaseDir,item))
				except:
					pass

		print(STLFiles)
		print(STLPath)
		print(len(STLFiles))
		print(len(STLPath))

		for Index,Mdlitem in enumerate(STLPath):
			RendFileNm = os.path.join(MdlBaseDir,(STLFiles[Index].rsplit(".",1)[0]+".png"))
			print(RendFileNm)
			App.newDocument("Unnamed")
			App.setActiveDocument("Unnamed")
			App.ActiveDocument=App.getDocument("Unnamed")
			Gui.ActiveDocument=Gui.getDocument("Unnamed")
			Mesh.insert(Mdlitem,"Unnamed")
			Gui.SendMsgToActiveView("ViewFit")
			Gui.activeDocument().activeView().setAnimationEnabled(False)
			Gui.activeDocument().activeView().viewAxonometric()
			Gui.activeDocument().activeView().saveImage(RendFileNm,1010,576,'Current')
			App.closeDocument("Unnamed")
			App.setActiveDocument("")
			App.ActiveDocument=None
			Gui.ActiveDocument=None


		#All thumbnails generated will end up in the selected base directory.  We will use
		#ImageMagick's montage command to build a contact sheet.
		CSheetBaseNm = "1-"+os.path.split(MdlBaseDir)[1]+"contact-sheet.png"
		print(CSheetBaseNm)
		TargDirFormats=os.path.join(MdlBaseDir,"*.png")
		BaseComm = ["montage","-verbose","-label","%f","-font","Arial","-pointsize","12","-background","#FFFFFF","-fill","black","-define","jpeg:size=400x","-geometry","400x+2+2","-tile","4x","-auto-orient"]
		FullComm = BaseComm+[TargDirFormats,CSheetBaseNm]
		print(FullComm)
		# montage -verbose -label '%f' -font Arial -pointsize 12 -background 'transparent' -fill 'black' -define jpeg:size=400x -geometry 400x+2+2 -tile 4x -auto-orient *.png contact-sheet.png
		subprocess.call(FullComm,shell=False)
		DoneBox=QtGui.QMessageBox.information(None,"","Done")

	def YepInclude(self):
		#SubDirSweep = not(SubDirSweep)	#Toggle the boolean
		if self.SubDirSweep == 0:
			self.SubDirSweep = 1
		else:
			self.SubDirSweep = 0
		#SubDirSweep=str(self.DirSweepchkbx.checkState())
		print(self.SubDirSweep)

	def FindDir(self):
		ThisDir = QtGui.QFileDialog.getExistingDirectory(self,"Select Target Directory",MdlBaseDir,QtGui.QFileDialog.ShowDirsOnly)
		if ThisDir is None: # dialoged return `None` if dialog closed with "cancel".
		        return
		else:
			os.chdir(ThisDir)
			self.InDirlabel.setText(ThisDir)

	def QuitNow(self):
		self.close()


# code ***********************************************************************************

form = ExampleModalGuiClass()
form.exec_()
