# 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 2
# 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.
#

import os
import bpy
from mathutils import Vector
from mathutils import Quaternion
from mathutils import Euler
from . import kex_utils
from . import turok_map
from bpy_extras.wm_utils.progress_report import (
    ProgressReport,
    ProgressReportSubstep,
)

# -----------------------------------------------------------------------------
#
def save(context,
         filepath,
         *,
         use_selection=True,
         global_matrix=None,
         path_mode='AUTO'
         ):
    return export_map(filepath, context)
#end func
# -----------------------------------------------------------------------------
#
def export_map(filepath, context):
    obj = context.object
    if obj is None:
        kex_utils.show_error("[Export Map] No Object Selected")
        return {'CANCELLED'}
        
    #check obj parents for a Turok Map Object and use that instead if found
    # while True:
        # if obj.parent is None or obj.parent.type != "ARMATURE":
            # break
        # obj = obj.parent

    #make sure selected object is a Turok Map Object
    # if obj.type != "ARMATURE":
        # kex_utils.show_error("[Export Anim] Cannot export a %s Object. Object must be an Armature." % (obj.type))
        # return {'CANCELLED'}
    
    #must have at least 1 actor,sector,staticmesh to export
    # if len(actions) == 0:
        # kex_utils.show_error("[Export Anim] No Animation Actions to export for this Armature.")
        # return {'CANCELLED'}
    
    map = turok_map.Map()
    #create map data from the Blender Objects
    
    with ProgressReport(context.window_manager) as progress:
        progress.enter_substeps(1)
        print("Exporting Turok Map %r ..." % filepath)

        #Save the .map file
        with open(filepath, 'wb') as data:
            map.write(data)
        #end with
        progress.leave_substeps("Map Successfully Exported!")
    #end with
    
    return {'FINISHED'}
#end func