# coding: utf-8
'''
Copyright (C) 2024 brothermechanic@yandex.com

Created by brothermechanic

    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 <http://www.gnu.org/licenses/>.
'''

import logging
import os
import bpy

logger = logging.getLogger(__name__)


def unlink_from_collections(context, obj):
    ''' Unlinking object from all collections. '''
    for col in list(bpy.data.collections) + [context.scene.collection]:
        if obj.name in col.objects:
            col.objects.unlink(obj)
    return obj


def link_library(lib_path, lib_type, lib_name):
    '''  '''
    bpy.ops.wm.link(
        filepath=lib_path,
        directory=os.path.join(lib_path, lib_type),
        filename=lib_name,
        relative_path=True,
        do_reuse_local_id=True,
        autoselect=True,
        instance_collections=True,
        instance_object_data=True
        )
    return bpy.data.objects[lib_name]


def switch_3d_entities(context, lib_dir):
    '''  '''
    assert bpy.data.collections.get('visual'), 'No visual collection!'
    entities_from = bpy.data.collections['visual'].objects
    assert os.path.isdir(lib_dir), 'No libs dir {}!'.format(lib_dir)
    lib_files = os.listdir(lib_dir)

    hp_col = bpy.data.collections.new('Parts')
    context.scene.collection.children.link(hp_col)
    for entity_from in entities_from:
        for lib_file in lib_files:
            if '{}_hp.blend'.format(entity_from.name) != lib_file:
                continue

            entity_to = link_library(
                lib_path=os.path.join(lib_dir, lib_file),
                lib_type='Collection',
                lib_name='{}_hp'.format(entity_from.name))

            entity_to.empty_display_type = 'ARROWS'
            entity_to.empty_display_size = 0.5

            unlink_from_collections(context, entity_to)
            hp_col.objects.link(entity_to)

            entity_to.location = entity_from.location
            entity_from.rotation_mode = entity_to.rotation_mode = 'QUATERNION'
            entity_to.rotation_quaternion = entity_from.rotation_quaternion
            entity_to.scale = entity_from.scale

            entity_to.parent = entity_from.parent

            logger.info('Entity %s changed to %s!', entity_from.name, entity_to.name)

    bpy.data.collections['visual'].hide_render = True
    bpy.data.collections['visual'].hide_viewport = True

    return True
