# coding: utf-8
# Copyright (C) 2023 Ilia Kurochkin <brothermechanic@yandex.com>
#
# 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.
'''
DESCRIPTION.
Collecting all parents and reconstruct this hierarhy in bledner.
'''
__version__ = '0.3'
import logging
import bpy
from mathutils import Vector

logger = logging.getLogger(__name__)


def fc_placement(bobj, fc_location, fc_rotation, scene_scale):
    ''' Prepare FreeCAD's Placement and Quaternion for Blender '''
    bobj.location = Vector(fc_location) * scene_scale
    m = bobj.rotation_mode
    bobj.rotation_mode = 'QUATERNION'
    # FreeCAD Quaternion is XYZW while Blender is WXYZ
    fc_rotation.insert(0, fc_rotation.pop(3))
    bobj.rotation_quaternion = fc_rotation
    bobj.rotation_mode = m
    return bobj


def hierarchy_list(bobj, hierarchy, scene_scale):
    ''' Blender object, dict, Blender World Scale factor. '''
    hierarchy_objs = []
    for parent_name in hierarchy.keys():
        if bpy.data.objects.get(parent_name):
            empty = bpy.data.objects[parent_name]
        else:
            empty = bpy.data.objects.new(parent_name, None)
            empty.empty_display_type = 'CUBE'
            empty.empty_display_size = 0.01
            fc_placement(empty,
                         hierarchy[parent_name]['fc_location'],
                         hierarchy[parent_name]['fc_rotation'],
                         scene_scale)
            empty.select_set(False)
            hierarchy_objs.append(empty)

        if hierarchy[parent_name]['deep_index'] == 0:
            bobj.parent = empty

        logger.debug('Add parent %s to object %s', bobj.parent.name, bobj.name)

    for parent_name in hierarchy.keys():
        parent_parenta_name = hierarchy[parent_name]['parent']
        if parent_parenta_name:
            bpy.data.objects[parent_name].parent = bpy.data.objects[
                parent_parenta_name]

    return hierarchy_objs
