# -*- coding: utf-8 -*-
"""gui_api tutorial 2: a tool window with widgets and callbacks.

The window stays open after the script ends. Every button, input and menu item calls back into
this script when the user uses it.
"""
import os
import subprocess
import sys

import export_api
import gui_api
import pattern_api
import utility_api

if not gui_api.IsGuiAvailable():
    raise SystemExit("gui_api needs the CLO window (it is not available in headless mode)")

gui_api.CloseAllWindows()  # running the script again replaces the old window

OUTPUT = os.path.join(os.path.expanduser("~"), "Documents", "CLO", "QuickExport").replace(os.sep, "/")
ui = {}


def open_folder(path):
    os.makedirs(path, exist_ok=True)
    if sys.platform.startswith("win"):
        os.startfile(path)
    else:
        subprocess.Popen(["open", path])


window = gui_api.CreateToolWindow("Quick Export", 460, 560)

# --- menu bar ---------------------------------------------------------------
file_menu = gui_api.AddMenu(window, "File")
gui_api.AddMenuItem(file_menu, "Open output folder", lambda: open_folder(OUTPUT))
gui_api.AddMenuItem(file_menu, "Close", lambda: gui_api.CloseWindow(window))

# --- inputs -----------------------------------------------------------------
settings = gui_api.AddGroup(window, "Settings")
ui["name"] = gui_api.AddTextInput(settings, utility_api.GetProjectName() or "untitled", "file name")
row = gui_api.AddRow(settings)
gui_api.AddLabel(row, "View")
ui["view"] = gui_api.AddDropdown(row, ["3D window", "2D window", "Both"], 0)
ui["open"] = gui_api.AddCheckBox(settings, "Open the folder when done", False)
gui_api.AddLabel(settings, "Repeat count")
ui["count"] = gui_api.AddSlider(settings, 1, 1, 5, lambda v: gui_api.SetWidgetText(ui["count_label"], "%d file(s) per view" % v))
ui["count_label"] = gui_api.AddLabel(settings, "1 file(s) per view")

# --- actions ----------------------------------------------------------------
gui_api.AddSeparator(window)
actions = gui_api.AddRow(window)
ui["progress"] = gui_api.AddProgressBar(window, 0)
ui["log"] = gui_api.AddTextArea(window, "", True)
lines = []


def log(text):
    lines.append(text)
    gui_api.SetWidgetValue(ui["log"], chr(10).join(lines[-50:]))


def export():
    os.makedirs(OUTPUT, exist_ok=True)
    base = gui_api.GetWidgetValue(ui["name"]).strip() or "untitled"
    view = gui_api.GetWidgetSelectedIndex(ui["view"])
    count = int(gui_api.GetWidgetValue(ui["count"]))
    jobs = []
    if view in (0, 2):
        jobs.append(("3d", export_api.ExportThumbnail3D))
    if view in (1, 2):
        jobs.append(("2d", export_api.ExportThumbnail2D))
    total, done = len(jobs) * count, 0
    for tag, fn in jobs:
        for n in range(count):
            path = "%s/%s_%s_%d.png" % (OUTPUT, base, tag, n + 1)
            log(("saved " if fn(path) else "failed ") + path)
            done += 1
            gui_api.SetWidgetValue(ui["progress"], str(int(done * 100 / total)))
    log("%d pattern(s) in the scene" % pattern_api.GetPatternCount())
    if gui_api.GetWidgetValue(ui["open"]) == "true":
        open_folder(OUTPUT)


gui_api.AddButton(actions, "Export", export)
gui_api.AddButton(actions, "Clear log", lambda: (lines.clear(), gui_api.SetWidgetValue(ui["log"], "")))
gui_api.SetWindowCloseCallback(window, lambda: print("Quick Export closed"))

gui_api.ShowWindow(window)
# The script ends here. The window and its callbacks stay alive.
