# ##### BEGIN GPL LICENSE BLOCK #####
#
#  Copyright (C) 2022 VFX Grace - All Rights Reserved
#
#  This program is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <https://www.gnu.org/licenses/>.
#
# ##### END GPL LICENSE BLOCK #####

bl_info = {
    "name": "3D Hair Brush",
    "author": "",
    "version": (3, 2, 0),
    "blender": (2, 93, 0),
    "location": "VIEW3D->Tools(Particle mode), Render->Render Engine",
    "description": "3D hair brush and CyclesHair render engine.",
    "warning": "",
    "category": "Particle",
}

import bpy
from . import hair_brush_3d
from . import cycles_hair_engine
from . import hair_modifier
from bpy.types import AddonPreferences
from bpy.props import BoolProperty
from bpy.utils import unregister_class, register_class


def register_keymaps():
    addon = bpy.context.window_manager.keyconfigs.addon
    if addon is None:
        return

    pref = bpy.context.preferences.addons[__package__].preferences
    keymaps = addon.keymaps
    if 'Window' not in keymaps:
        keymaps.new(name='Window')

    kms = keymaps['Window'].keymap_items
    kms.new('particle.brush_pie_menu', 'V', 'PRESS')
    if pref.brush_opt_menu:
        kmi = kms.new('wm.call_menu_pie', 'J', 'PRESS')
        kmi.properties.name = "VIEW3D_MT_hair_brush_opt"


def unregister_keymaps():
    addon = bpy.context.window_manager.keyconfigs.addon
    if addon is None:
        return
    keymaps = addon.keymaps
    if 'Window' in keymaps:
        kms = keymaps['Window'].keymap_items
        for kmi in kms:
            if kmi.idname == "particle.brush_pie_menu":
                kms.remove(kmi)
            elif kmi.idname == "wm.call_menu_pie" and kmi.properties.name == "VIEW3D_MT_hair_brush_opt":
                kms.remove(kmi)


class HairBrush3dPref(AddonPreferences):
    bl_idname = __package__

    def update_opt_menu(self, context):
        addon = bpy.context.window_manager.keyconfigs.addon
        if addon is None:
            return
        keymaps = addon.keymaps
        if 'Window' not in keymaps:
            keymaps.new(name='Window')
        kms = keymaps['Window'].keymap_items
        if self.brush_opt_menu:
            kmi = kms.new('wm.call_menu_pie', 'J', 'PRESS')
            kmi.properties.name = "VIEW3D_MT_hair_brush_opt"
        else:
            for kmi in kms:
                if kmi.idname == "wm.call_menu_pie" and kmi.properties.name == "VIEW3D_MT_hair_brush_opt":
                    kms.remove(kmi)

    def update_hair_modifiers(self, context):
        if self.hair_modifiers:
            hair_modifier.register()
        else:
            hair_modifier.unregister()

    collapse_intern: BoolProperty(
        name="Fold Default Brushes",
        default=True,
        description="Fold all the default hair brushes")

    brush_opt_menu: BoolProperty(
        name="Enable Brush Option Menu",
        default=True,
        update=update_opt_menu,
        description="Show the shortcut menu")

    hair_modifiers: BoolProperty(
        name="Enable Modifier of Hair Children",
        default=True,
        update=update_hair_modifiers)

    def draw_short_cut(self, box, kmi, label):
        if kmi:
            row = box.row()
            row.alignment = "LEFT"
            row.label(text=label)
            if bpy.app.version < (3, 0):
                row.prop(kmi, "ctrl", text="Ctrl")
                row.prop(kmi, "shift", text="Shift")
                row.prop(kmi, "alt", text="Alt")
            else:
                row.prop(kmi, "ctrl_ui", text="Ctrl")
                row.prop(kmi, "shift_ui", text="Shift")
                row.prop(kmi, "alt_ui", text="Alt")
            row.prop(kmi, "type")

    def draw(self, context):
        box = self.layout.box()
        box.prop(self, "hair_modifiers")
        box.prop(self, "collapse_intern")

        kms = context.window_manager.keyconfigs.user.keymaps['Window'].keymap_items
        kmi = kms.get("particle.brush_pie_menu", None)
        self.draw_short_cut(box, kmi, 'Pie Menu Shortcut')

        box.prop(self, "brush_opt_menu")
        if self.brush_opt_menu:
            for kmi in kms:
                if kmi.idname == "wm.call_menu_pie" and kmi.properties.name == "VIEW3D_MT_hair_brush_opt":
                    self.draw_short_cut(box, kmi, 'Option Menu Shortcut')
                    break


modules = [cycles_hair_engine, ]
if not bpy.app.background:
    modules.append(hair_brush_3d)


def register():
    if bpy.app.version < (2, 93) or bpy.app.version >= (3, 3):
        raise NotImplementedError("This addon supports Blender 2.93-3.2 only!")

    for addon in bpy.context.preferences.addons:
        if addon.module.startswith("3D Hair Brush Viewer"):
            raise Exception('You already have "3D Hair Brush Viewer" installed, Please uninstall it and retry!')

    register_class(HairBrush3dPref)
    for mod in modules:
        mod.register()

    if bpy.context.preferences.addons[__package__].preferences.hair_modifiers:
        hair_modifier.register()

    register_keymaps()


def unregister():
    if bpy.context.preferences.addons[__package__].preferences.hair_modifiers:
        hair_modifier.unregister()

    unregister_keymaps()
    unregister_class(HairBrush3dPref)
    for mod in modules:
        mod.unregister()


if __name__ == "__main__":
    register()
