#=============================================================================
#
#  Copyright (c) Kitware, Inc.
#  All rights reserved.
#  See LICENSE.txt for details.
#
#  This software is distributed WITHOUT ANY WARRANTY; without even
#  the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
#  PURPOSE.  See the above copyright notice for more information.
#
#=============================================================================
"""
Export script for Proteus-SN workflows
"""
import os
import sys

from . import export_to_proteus_sn_xml

import smtk
import smtk.attribute
import smtk.io
import smtk.model

import rggsession

# Add the directory containing this file to the python module search list
import inspect
sys.path.insert(0, os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))))

from .proteus_sn_writer import *

class export_to_proteus_sn(smtk.operation.Operation):

    def __init__(self):
        smtk.operation.Operation.__init__(self)

    def name(self):
        return "export to Proteus-SN"

    def operateInternal(self):
        result = self.createResult(smtk.operation.Operation.Outcome.FAILED)

        try:
            success = ExportCMB(self.parameters(), self.log())
        except:
            smtk.ErrorMessage(self.log(), str(sys.exc_info()[0]))
            raise

        # Return with success
        if success:
            result = self.createResult(smtk.operation.Operation.Outcome.SUCCEEDED)
        return result

    def createSpecification(self):
        spec = smtk.attribute.Resource.create()
        reader = smtk.io.AttributeReader()
        reader.readContents(spec, export_to_proteus_sn_xml.description, self.log())
        return spec

ExportScope = type('ExportScope', (object,), dict())
# ---------------------------------------------------------------------
def ExportCMB(operator_spec, log):
    '''Entry function, called by CMB to write export files

    Returns boolean indicating success
    Parameters
    ----------
    spec: Top-level object passed in from CMB
    '''

    # Initialize scope instance to store spec values and other info
    scope = ExportScope()

    scope.logger = log
    scope.export_att = operator_spec
    scope.sim_atts = smtk.attribute.Resource.CastTo(operator_spec.find('attributes').value())
    if scope.sim_atts is None:
        msg = 'ERROR - No simlation attributes'
        print msg
        raise RuntimeError(msg)

    scope.model_entity = smtk.model.Entity.CastTo(operator_spec.find('model').value(0))
    scope.model_resource = scope.model_entity.modelResource()
    if scope.model_resource is None:
        msg = 'ERROR - No model'
        print msg
        raise RuntimeError(msg)
    scope.model_path = scope.model_resource.location()
    scope.model_file = os.path.basename(scope.model_path)

    scope.mesh_resource = smtk.mesh.Resource.CastTo(operator_spec.find('mesh').value(0))
    if scope.mesh_resource is None:
        msg = 'ERROR - No mesh'
        print msg
        raise RuntimeError(msg)

    # Get output filename (path)
    output_path = None
    dir_item = operator_spec.findDirectory('OutputDirectory')
    if dir_item is not None:
        output_path = dir_item.value(0)
    if not output_path:
        raise RuntimeError('No output directory specified')

    # Generate output directory if needed
    if not os.path.exists(output_path):
        print('Creating directory {}'.format(output_path))
        os.makedirs(output_path)
    scope.output_path = output_path

    writer = ProteusSNWriter()
    success = writer.write(scope)

    return success
