# ##### 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 #####

import bpy
from .particle_hook import particle_hook
from ..cycles_hair_engine.draw_engine.draw_data import EditHairColorDrawData, ColorUpdateFlag


G_hair_color_draw_data = None
G_hair_color_draw_handler = None


def edit_hair_color_draw_cb(context):
    global G_hair_color_draw_data
    if G_hair_color_draw_data is None or context.mode != 'PARTICLE':
        return
    obj = context.object
    if (not obj or obj.mode != 'PARTICLE_EDIT' or not obj.particle_systems
            or obj.particle_systems.active.settings.type != 'HAIR'):
        return
    if not context.space_data or context.space_data.type != 'VIEW_3D':
        return
    strands_res = max(1 << context.tool_settings.particle_edit.display_step, 4) + 1
    G_hair_color_draw_data.draw(context.space_data.region_3d, strands_res)


def update_hair_color(context, update_flag):
    global G_hair_color_draw_data
    if G_hair_color_draw_data is None:
        return
    G_hair_color_draw_data.update_data(context, update_flag)


def show_hair_color(context, show=True):
    global G_hair_color_draw_handler
    global G_hair_color_draw_data
    if show:
        if G_hair_color_draw_handler is None:
            G_hair_color_draw_data = EditHairColorDrawData(context, particle_hook.get_hair_color)
            update_hair_color(context, ColorUpdateFlag.FORCE_TEX)
            G_hair_color_draw_handler = bpy.types.SpaceView3D.draw_handler_add(
                edit_hair_color_draw_cb, (context, ), 'WINDOW', 'POST_VIEW')
    elif G_hair_color_draw_handler:
        bpy.types.SpaceView3D.draw_handler_remove(G_hair_color_draw_handler, 'WINDOW')
        G_hair_color_draw_handler = None
        G_hair_color_draw_data = None
