from .. import __package__ as base_package
import bpy
from bpy.types import Operator
from bpy.props import StringProperty, BoolProperty, IntProperty
from .funcs import select_all, set_active, get_scene_workspaces, set_scene_workspaces, get_use_topbar, has_data, prefs, tag_redraw_topbar


class SW_OT_switch(Operator):
    bl_idname = "sw.switch"
    bl_label = "Show/Hide Scene Workspaces"
    bl_description = "Switch workspaces topbar between Scene Workspaces and default"

    def execute(self, context):
        prefs().use_topbar = not get_use_topbar()
        context.preferences.is_dirty = True
        return {'FINISHED'}


class SW_OT_workspace(Operator):
    bl_idname = "sw.workspace"
    bl_label = "Workspace"
    bl_description = "Make this workspace active (or remove it from the scene, if missing)"

    workspace: StringProperty(name="workspace")

    def invoke(self, context, ev):
        if self.workspace in [x.name for x in bpy.data.workspaces]:
            bpy.context.window.workspace = bpy.data.workspaces[self.workspace]
        else:
            l = get_scene_workspaces()
            l.pop(l.index(self.workspace))
            set_scene_workspaces(l)
        return {'FINISHED'}
    
class SW_OT_select(Operator):
    bl_idname = "sw.select"
    bl_label = "Workspace"
    bl_description = "Select this workspace to reorder, rename or unlink"

    workspace: StringProperty(name="workspace")

    def execute(self, context):
        set_active(get_scene_workspaces().index(self.workspace))
        return {'FINISHED'}

class SW_OT_link_all(Operator):
    bl_idname = "sw.link_all"
    bl_label = "Link all workspaces to this Scene"
    bl_description = "Link all workspaces avaliable to this scene"

    def execute(self, context):
        select_all()
        return {'FINISHED'}


class SW_OT_move(Operator):
    bl_idname = "sw.move"
    bl_label = "Reorder Workspace"
    bl_description = "Reorder this workspace in the desired location (only for this Scene)"

    # 0 means using `top` for reorder back/front
    up: IntProperty(name="up", default=0)
    index: IntProperty(name="index", default=-1)
    top: BoolProperty(name="top", default=False)
    
    def valid(self, context):
        l = get_scene_workspaces()
        i = self.index if self.index != -1 else l.index(bpy.context.window.workspace.name)
        max_i = len(l) - 1
        return (self.up == 1 and i > 0) or (self.up == -1 and i < max_i) or (self.up == 0 and ((self.top and i > 0) or (not self.top and i < max_i)))

    def execute(self, context):
        l = get_scene_workspaces()
        if self.valid(context):
            try:
                i = self.index if self.index != -1 else l.index(bpy.context.window.workspace.name)
                new_i = 0 if self.top else len(l)-1
                if self.up == 0:
                    l.insert(new_i, l.pop(i))
                else:
                    new_i = i-self.up
                    l.insert(new_i, l.pop(i))

                set_active(new_i)
                set_scene_workspaces(l)
                self.up = 0
                self.top = False
            except:
                pass
        return {'FINISHED'}


class SW_OT_activate(Operator):
    bl_idname = "sw.activate"
    bl_label = "Activate Next/Previous Workspace"

    next: BoolProperty(name="next")

    @classmethod
    def description(cls, context, props):
        return f"Activate {'the next' if props.next else 'the previous'} workspace"

    def execute(self, context):
        l = get_scene_workspaces()
        ws = bpy.data.workspaces
        try:
            active_i = l.index(bpy.context.window.workspace.name)
            w = None
            if self.next:
                if active_i < len(l)-1:
                    w = ws[l[active_i+1]]
                else:
                    w = ws[l[0]]
            else:
                if active_i == 0:
                    w = ws[l[len(l)-1]]
                else:
                    w = ws[l[active_i-1]]
            bpy.context.window.workspace = w
        except:
            pass
        return {'FINISHED'}


class SW_OT_rename(Operator):
    bl_idname = "sw.rename"
    bl_label = "Rename workspace"
    bl_description = "Rename the current workspace (this rename both the global workspace as the scene workspace)"

    current_name: StringProperty(name="Current Name", options={'HIDDEN'})
    new_name: StringProperty(
        name="Name",
        description="The new name for this workspace", default="")

    def execute(self, context):
        w = bpy.data.workspaces[self.current_name]
        # Update global workspace name
        w.name = self.new_name
        # Update name in all scenes, if present, to avoid missing workspace
        for s in bpy.data.scenes:
            l = get_scene_workspaces(s.name)
            try:
                i = l.index(self.current_name)
                l.pop(i)
                l.insert(i, self.new_name)
                set_scene_workspaces(l, s.name)
            except:
                pass
        return {'FINISHED'}

    def invoke(self, context, event):
        return context.window_manager.invoke_props_dialog(self, title=f"Rename Workspace '{self.current_name}'")


class SW_OT_remove(Operator):
    bl_idname = "sw.remove"
    bl_label = "Unlink Workspace"
    bl_description = "Unlink this workspace from this scene (this will not delete the workspace)"

    index: IntProperty(name="index", default=-1)

    def execute(self, context):
        l = get_scene_workspaces()
        l.pop(self.index)
        set_scene_workspaces(l)
        set_active(max(0, self.index-1))
        return {'FINISHED'}


class SW_OT_copy_from_scene(Operator):
    bl_idname = "sw.copy_from_scene"
    bl_label = "Copy from another Scene"
    bl_description = "Copy linked workspaces from this scene"

    scene: StringProperty(name="scene")

    def execute(self, context):
        l = get_scene_workspaces(self.scene)
        set_scene_workspaces(l)
        return {'FINISHED'}


class SW_OT_link_workspace(Operator):
    bl_idname = "sw.link_workspace"
    bl_label = "Link Workspace"

    workspace: StringProperty(name="workspace")

    @classmethod
    def description(cls, context, props):
        return "This is the active workspace, but it's not linked to this scene. Click to link" if props.workspace == bpy.context.window.workspace.name else "Link this workspace to this Scene"

    def execute(self, context):
        if not has_data():
            set_active()
            set_scene_workspaces([])
        if self.workspace in get_scene_workspaces():
            set_scene_workspaces(
                [x for x in get_scene_workspaces() if x != self.workspace])
            set_active(len(get_scene_workspaces()) - 1)
        else:
            set_scene_workspaces([*get_scene_workspaces(), self.workspace])
            set_active(len(get_scene_workspaces()) - 1)
        return {'FINISHED'}
