# Copyright (C) <2021>  <Reston Stanton>

# ##### BEGIN GPL LICENSE BLOCK #####
#
# 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
# MERCHANTIBILITY 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 <http://www.gnu.org/licenses/>.
#
# ##### END GPL LICENSE BLOCK #####


import bpy
from . import material


def make_domain_bounds(context, domain):
    """adds domain bounds to scene"""
    bpy.ops.object.select_all(action='DESELECT')
    override = context.copy()
    override['selected_objects'] = [domain, ]
    override['active_object'] = domain
    bpy.ops.object.duplicate_move(override,
                                  OBJECT_OT_duplicate={"linked": True, "mode": 'TRANSLATION'})

    overlay = context.selected_objects[-1]

    if "Fluid" in overlay.modifiers:
        override = context.copy()
        override['object'] = overlay
        bpy.ops.object.modifier_remove(override, modifier="Fluid")

    overlay.display_type = 'BOUNDS'
    overlay.hide_select = True
    overlay.hide_render = True
    overlay.name = "DOMAIN_BOUNDS_" + domain.name.upper()

    override = context.copy()
    override['selected_editable_objects'] = [domain, overlay]
    override['object'] = domain

    overlay.material_slots[0].link = 'OBJECT'
    material.add_material(overlay, "TRANSPARENT")

    bpy.ops.object.parent_set(override)


def toggle_doamin_bounds(context, domain):
    """toggle domain bounds"""
    for obj in domain.children:
        if "DOMAIN_BOUNDS" in obj.name:
            if obj.hide_viewport:
                obj.hide_viewport = False
            else:
                obj.hide_viewport = True
            return True

    make_domain_bounds(context, domain)


def find_bounds(domain):
    """find bounds object"""
    bounds = None
    for obj in domain.children:
        if "DOMAIN_BOUNDS" in obj.name:
            bounds = obj
    return bounds
