# Begin Batch Renderer Macro - STL_STEP_Renderv8-py36-IM6.FCMacro
#For FreeCAD with Python 3 and ImageMagick 6

import FreeCAD
import Mesh
import os
from tkinter import *
from tkinter import filedialog
import subprocess

# This edition introduces a Tkinter file dialogue to navigate to the target directory

root = Tk()

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


def FindDir():
    ThisDir = filedialog.askdirectory(title="Please select a directory to process")
    if (ThisDir is None):  # asksaveasfile return `None` if dialog closed with "cancel".
        return
    os.chdir(ThisDir)
    InLocation.set(ThisDir)
    return ThisDir


def CloseDown():
    root.destroy()


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

    # This is if the sweep through subdirectory check box is ticked
    if SubDirSweep.get() == True:
        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","transparent","-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)


# Building The Interface
InLocation = StringVar()
InDirlabel = Label(root, textvariable=InLocation)
InLocation.set(MdlBaseDir)
InDirlabel.grid(row=0, column=0)

# Button to Change the directory
inDirButtn = Button(root, text="Change", command=FindDir)
inDirButtn.grid(row=0, column=1)

# Checkbox for going through the subdirectories option
SubDirSweep = (IntVar())  # set the variable to accept the state of the checkbox.
SubDirSweepCk = Checkbutton(root,text="Include Subdirectories?",variable=SubDirSweep)
SubDirSweepCk.grid(row=1, column=0)

# Buttons to start process and quit dialogue
GoButtn = Button(root, text="Go", command=ProcessDir)
GoButtn.grid(row=2, column=0)

CancelButtn = Button(root, text="Quit", command=CloseDown)
CancelButtn.grid(row=2, column=1)

root.mainloop()


# Macro End:
