import bpy

from ..utils import get_export_path, get_asset_name


class ExportForFange(bpy.types.Operator):
    """Export a building for fange.
Requiert your blend file are write on your hard-drive."""
    bl_idname = 'graou.building_export'
    bl_label = 'Easily export a building asset'

    def __init__(self):
        self.coll_layout = bpy.data.collections.get('Placeholder')
        self.asset = get_asset_name()
        self.category = get_export_path()

        self.instance_type_dict = {}
        self.temp_copy = {}

    @classmethod
    def poll(cls, context):
        col = bpy.data.collections.get('Placeholder')

        if col is not None and bpy.data.is_saved:
            return True

    def execute(self, context):
        bpy.ops.object.select_all(action='DESELECT')

        # Make a check if the file are saved on the disk
        if not bpy.data.is_saved:
            self.report({'ERROR'}, 'Your blend file is not saved.')
            return {'CANCELLED'}

        if not self.category:
            self.report({'ERROR'}, 'Can\'t find the asset category.')
            return {'CANCELLED'}

        if not len(self.coll_layout.children):
            self.report({'WARNING'}, 'No children collection, nothing can be exported.')
            return {'CANCELLED'}

        for coll in self.coll_layout.children:
            print(f'[Pipeline] Update "{coll.name}" mesh')
            child = bpy.data.collections.get(coll.name)

            for ob in child.all_objects:
                print(f'\tLook "{ob.name}", his type are "{type(ob.data)}"')
                # TODO Support another type object, not only SM/SK
                if ob.type == 'MESH' or 'EMPTY' or 'CURVE':
                    print(f'[Pipeline] Check ob {ob.name} and is type {type(ob)}')
                    ob.select_set(True)

                    if ob.type == 'EMPTY':
                        if ob.instance_type != 'NONE':
                            self.instance_type_dict[ob.name] = ob.instance_type
                            ob.instance_type = 'NONE'

                    if ob.type == 'CURVE':
                        # Make a new objet with the Geo
                        bpy.ops.object.convert(target='CURVE')

            abs_export = self.category.joinpath(self.asset, "Meshes")
            if not abs_export.exists():
                abs_export.mkdir(parents=True)

            if coll.name != 'Socket':
                asset_name = f"SM_{coll.name}.fbx"
            else:
                asset_name = f"{coll.name}.fbx"

            # TODO Use the preset system
            bpy.ops.export_scene.fbx(filepath=abs_export.joinpath(asset_name).as_posix(),
                                     use_selection=True,
                                     use_visible=False,
                                     use_active_collection=False,
                                     global_scale=1.0,
                                     apply_unit_scale=True,
                                     apply_scale_options='FBX_SCALE_NONE',
                                     use_space_transform=True,
                                     bake_space_transform=True,
                                     object_types={'MESH', 'EMPTY'},
                                     use_mesh_modifiers=True,
                                     use_mesh_modifiers_render=True,
                                     mesh_smooth_type='OFF',
                                     colors_type='SRGB',
                                     prioritize_active_color=False,
                                     use_subsurf=False,
                                     use_mesh_edges=False,
                                     use_tspace=False,
                                     use_triangles=False,
                                     use_custom_props=False,
                                     add_leaf_bones=True,
                                     primary_bone_axis='Y',
                                     secondary_bone_axis='X',
                                     use_armature_deform_only=False,
                                     armature_nodetype='NULL',
                                     bake_anim=False,
                                     bake_anim_use_all_bones=True,
                                     bake_anim_use_nla_strips=True,
                                     bake_anim_use_all_actions=True,
                                     bake_anim_force_startend_keying=True,
                                     bake_anim_step=1.0,
                                     bake_anim_simplify_factor=1.0,
                                     path_mode='AUTO',
                                     embed_textures=False,
                                     batch_mode='OFF',
                                     use_batch_own_dir=True,
                                     axis_forward='X',
                                     axis_up='Y'
                                     )

            print(f'[Pipeline] Export here "{abs_export}"')
            bpy.ops.object.select_all(action='DESELECT')

            self.set_instance_type()

        self.report({'INFO'}, 'Placeholder exported')
        return {'FINISHED'}

    def set_instance_type(self):
        for key, value in self.instance_type_dict.items():
            ob = bpy.data.objects.get(key)
            ob.instance_type = value

        self.instance_type_dict.clear()
