import bpy
from bpy.types import Panel
from .funcs import prop_name, prop_i_name, get_active, get_scene_workspaces, workspace_ops

class SW_PT_select_scene_workspaces(Panel):
    bl_idname = "sw.select_scene_workspaces"
    bl_label = "Scene Workspaces"
    bl_space_type = 'PROPERTIES'
    bl_region_type = 'WINDOW'
    bl_context = "scene"
    bl_options = {'DEFAULT_CLOSED'}

    def draw(self, context):
        layout = self.layout
        layout.alignment = 'LEFT'
        layout.label(text="Workspaces linked to this Scene")
        row = layout.row()
        sw = get_scene_workspaces()
        if not sw:
            box = row.box()
            box.label(text="There are no workspaces linked right now...")
            box.operator("sw.link_all")
        else:
            i = get_active()
            active = sw[i]
            r = row.box().column(align=True)
            for w in sw:
                op = r.operator("sw.select", text=w, icon="RADIOBUT_ON" if active == w else "RADIOBUT_OFF", emboss=active == w)
                op.workspace = w
            r = row.column(align=True)
            workspace_ops(r, i, False, active)

        layout.separator()

        layout.label(text="Link other workspaces")
        box2 = layout.box()
        row = box2.row()
        row_count = 0
        l = [x for x in bpy.data.workspaces if x.name not in sw]
        for w in l:
            if row_count > 0 and row_count % 3 == 0:
                row = box2.row()
            row.operator("sw.link_workspace", text=w.name).workspace = w.name
            row_count += 1
        if l:
            layout.separator()
            layout.operator("sw.link_all")
        else:
            row.label(text="All workspaces are currently linked.")
