# Python imports
import faulthandler
import traceback
import logging
from datetime import datetime

# Gtk imports

# Application imports
from . import msh2_unpack


class MSH2():
    """docstring for MSH2."""

    def __init__(self, arg):
        faulthandler.enable()  # For better debug info
        self.arg        = arg
        self.msh_config = {'do_logging': True, 'ignore_geo': False, 'triangulate': False}
        self.msh        = None


    def get_mesh_obj(self):
        return self.msh

    def import_file(self, file_name):
        try:
            unpacker = msh2_unpack.MSHUnpack(file_name, self.msh_config)
            self.msh = unpacker.unpack()
        except Exception as e:
            traceback.print_exc()

    def export_file(self, file):
        logging.info('==========================================')
        logging.info('Starting export at {0}.'.format(datetime.now()))
        logging.info('.msh file path: {0}'.format(file))
        try:
            # Convert materials from Blender to msh2.
            # self.msh.materials = msh2.MaterialCollection(self.msh)
            # self.msh.materials.replace([])

            self.msh.models.assign_indices()
            self.msh.models.assign_parents()
            self.msh.models.remove_multi([])
            self.msh.models.assign_cloth_collisions()

            self.msh.save(file)
        except Exception as e:
            traceback.print_exc()

    def export_file_to_binary_json(self, file_name):
        try:
            self.msh.save_json(file_name)
        except Exception as e:
            traceback.print_exc()
