# -*- coding: utf-8 -*-
"""gui_api tutorial 3: a dock panel, like the Library or Object Browser.

The panel docks into the CLO main window, can be dragged to another side, floated or folded into the
side bar, and keeps its place the next time it is created with the same name.
"""
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 panel

panel = gui_api.CreateDockPanel("Pattern Browser", "right", "pattern_browser")
ui = {}


def refresh():
    count = pattern_api.GetPatternCount()
    rows = []
    for i in range(count):
        name = pattern_api.GetPatternPieceName(i) or "(unnamed)"
        area_cm2 = pattern_api.GetPatternPieceArea(i) / 100.0
        rows.append([str(i), name, "%.0f" % area_cm2])
    gui_api.SetTableRows(ui["table"], rows)
    gui_api.SetWidgetText(ui["status"], "%s - %d pattern(s)" % (utility_api.GetProjectName() or "(untitled)", count))
    gui_api.SetWidgetEnabled(ui["rename_row"], False)


def on_select(row):
    if row < 0:
        return
    pattern_api.SelectPatternViaIndex(row, False)  # highlight the piece in the 2D / 3D windows
    gui_api.SetWidgetValue(ui["new_name"], pattern_api.GetPatternPieceName(row))
    gui_api.SetWidgetEnabled(ui["rename_row"], True)


def rename():
    row = gui_api.GetWidgetSelectedIndex(ui["table"])
    new_name = gui_api.GetWidgetValue(ui["new_name"]).strip()
    if row >= 0 and new_name:
        pattern_api.SetPatternPieceName(row, new_name)
        refresh()
        gui_api.SetWidgetSelectedIndex(ui["table"], row)


ui["status"] = gui_api.AddLabel(panel, "")
ui["table"] = gui_api.AddTable(panel, ["#", "Pattern", "Area (cm2)"], [], on_select)

ui["rename_row"] = gui_api.AddRow(panel)
ui["new_name"] = gui_api.AddTextInput(ui["rename_row"], "", "new name")
gui_api.AddButton(ui["rename_row"], "Rename", rename)

gui_api.AddButton(panel, "Refresh", refresh)

refresh()
gui_api.ShowWindow(panel)
