 # ##### 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 version 2
#  as published by the Free Software Foundation.
#
#  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, write to the Free Software Foundation,
#  Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#


from .msh2 import msh2


msh_handler = msh2.MSH2(None)
bl_info     = {
    "name": "Zero Editor MSH2 format",
    "author": "Maxim Stewart",
    "version": (0, 0, 1),
    "blender": (2, 74, 0),
    "location": "File > Import-Export",
    "description": "Import-Export Zero Editor MSH2 models, meshs, and textures",
    "warning": "",
    "wiki_url": "https://schlechtwetterfront.github.io/ze_filetypes/msh.html",
    "category": "Import-Export"}

if "bpy" in locals():
    import importlib
    if "import_msh2" in locals():
        importlib.reload(import_msh2)
    if "export_msh2" in locals():
        importlib.reload(export_msh2)


import bpy
from bpy.props import (
        CollectionProperty,
        BoolProperty,
        FloatProperty,
        StringProperty,
        EnumProperty,
        )
from bpy_extras.io_utils import (
        ImportHelper,
        ExportHelper,
        orientation_helper_factory,
        path_reference_mode,
        axis_conversion,
        )

from bpy.types import OperatorFileListElement

# NOTE: NEED to see what ZERO Engine uses as forward
IOOBJOrientationHelper = orientation_helper_factory("IOOBJOrientationHelper", axis_forward='-Z', axis_up='Y')


class ImportMSH2(bpy.types.Operator, ImportHelper, IOOBJOrientationHelper):
    """Load a MSH2 File"""
    bl_idname  = "import_zero_editor_msh2.msh"
    bl_label   = "Zero Editor Import MSH2"
    bl_options = {'REGISTER', 'UNDO'}

    filename_ext = ".msh"
    filter_glob  = StringProperty(
            default = "*.msh;*.tga",
            options = {'HIDDEN'},
            )

    files = CollectionProperty(
            name="File Path",
            type=OperatorFileListElement,
            )
    directory = StringProperty(
            subtype='DIR_PATH',
            )


    use_image_search = BoolProperty(
            name="Image Search",
            description="Search subdirs for any associated images "
                        "(Warning, may be slow)",
            default=True,
            )

    def execute(self, context):
        keywords = self.as_keywords(ignore=("axis_forward",
                                            "axis_up",
                                            "filter_glob",
                                            "split_mode",
                                            ))

        keywords["use_cycles"] = (context.scene.render.engine == 'CYCLES')
        if bpy.data.is_saved and context.user_preferences.filepaths.use_relative_paths:
            import os
            keywords["relpath"] = os.path.dirname(bpy.data.filepath)

        data  = {**keywords}
        msh_handler.import_file(data["filepath"])
        msh   = msh_handler.get_mesh_obj()
        sceen = bpy.context.scene

        # Test adding mesh2 to blender
        for model in msh.models:
            name = model.name.decode("utf-8")
            # print(model)
            # print(model.name)
            # print(model.index)
            # print(model.collection)
            # print("")
            # Create a mesh data block
            mesh2 = bpy.data.meshes.new("{}".format(name))

            verts = []
            edges = []
            faces = []
            segments = model.segments
            for segment in segments:
                if segment.classname == "SegmentGeometry":
                    vertices = segment.vertices
                    for vert in vertices:
                        x = vert.x
                        y = vert.y
                        z = vert.z
                        verts.append((x, y, z))

                    sfaces = segment.faces
                    for face in sfaces:
                        '''Using CCW order for importing.'''
                        faces.append(face.SIindices())

            # Add the vertices to the mesh
            mesh2.from_pydata(verts, edges, faces)

            # Create an object that uses the mesh data
            myobj = bpy.data.objects.new("{}_obj".format(name), mesh2)

            # Link the object to the scene
            sceen.objects.link(myobj)

        return {'FINISHED'}


    # def draw(self, context):
    #     layout = self.layout
    #
    #     row = layout.row(align=True)
    #     row.prop(self, "use_smooth_groups")
    #     row.prop(self, "use_edges")
    #
    #     box = layout.box()
    #     row = box.row()
    #     row.prop(self, "split_mode", expand=True)
    #
    #     row = box.row()
    #     if self.split_mode == 'ON':
    #         row.label(text="Split by:")
    #         row.prop(self, "use_split_objects")
    #         row.prop(self, "use_split_groups")
    #     else:
    #         row.prop(self, "use_groups_as_vgroups")
    #
    #     row = layout.split(percentage=0.67)
    #     row.prop(self, "global_clamp_size")
    #     layout.prop(self, "axis_forward")
    #     layout.prop(self, "axis_up")
    #
    #     layout.prop(self, "use_image_search")


class ExportMSH2(bpy.types.Operator, ExportHelper, IOOBJOrientationHelper):
    """Save a MSH2 File"""

    bl_idname  = "export_zero_editor_msh2.msh"
    bl_label   = 'Zero Editor Export MSH2'

    # # context group
    filename_ext = ".msh"
    filter_glob  = StringProperty(
            default = "*.msh;*.tga",
            options = {'HIDDEN'},
            )

    use_selection = BoolProperty(
            name  = "Selection Only",
            description = "Export selected objects only",
            default = False,
            )

    use_animation = BoolProperty(
            name="Animation",
            description="Write out an OBJ for each frame",
            default=False,
            )

    use_uvs = BoolProperty(
            name="Include UVs",
            description="Write out the active UV coordinates",
            default=True,
            )
    use_materials = BoolProperty(
            name="Write Materials",
            description="Write out the MTL file",
            default=True,
            )
    use_triangles = BoolProperty(
            name="Triangulate Faces",
            description="Convert all faces to triangles",
            default=False,
            )

    def execute(self, context):
        keywords = self.as_keywords(ignore=("axis_forward",
                                            "axis_up",
                                            "global_scale",
                                            "check_existing",
                                            "filter_glob",
                                            ))
        data = {**keywords}
        # msh.export_file()
        # print("")
        # print("")
        # print(context)
        # print("")
        # print("")
        msh.export_file(data["filepath"])
        return {'FINISHED'}





classes = (
    ImportMSH2,
    ExportMSH2,
)


def menu_import(self, context):
    self.layout.operator(ImportMSH2.bl_idname, text="Zero Editor MSH2 (.msh)")


def menu_export(self, context):
    self.layout.operator(ExportMSH2.bl_idname, text="Zero Editor MSH2 (.msh)")


def register():
    for cls in classes:
        bpy.utils.register_class(cls)

    bpy.types.INFO_MT_file_import.append(menu_import)
    bpy.types.INFO_MT_file_export.append(menu_export)


def unregister():
    bpy.types.INFO_MT_file_import.remove(menu_import)
    bpy.types.INFO_MT_file_export.remove(menu_export)

    for cls in classes:
        bpy.utils.unregister_class(cls)


if __name__ == "__main__":
    register()
