#=============================================================================
#
#  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 PyARC workflows
"""

import sys

#from PyARC import PyARC

sys.dont_write_bytecode = True

import smtk
if 'pybind11' == smtk.wrappingProtocol():
    import smtk.attribute
    import smtk.model
    import smtk.simulation

from internal.writers import pyarc_writer


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

    Returns boolean indicating success
    Parameters
    ----------
    spec: Top-level object passed in from CMB
    '''
    print 'Enter ExportCMB()'

    # Initialize scope instance to store spec values and other info
    scope = ExportScope()
    scope.logger = spec.getLogger()
    scope.sim_atts = spec.getSimulationAttributes()
    if scope.sim_atts is None:
        msg = 'ERROR - No simulation attributes'
        print msg
        raise Exception(msg)
    scope.model_manager = scope.sim_atts.refModelManager()
    mask = int(smtk.model.MODEL_ENTITY)
    model_ents = scope.model_manager.entitiesMatchingFlags(mask, True)
    if not model_ents:
        msg = 'No model - cannot export'
        print 'WARNING:', msg
        scope.logger.addWarning(msg)
        print 'Abort export - check logger'
        return False
    elif len(model_ents) > 1:
        msg = 'Multiple models - using first one'
        print 'WARNING:', msg
        scope.logger.addWarning(msg)
    scope.model_ent = model_ents.pop()

    # Get export spec attribute
    scope.export_atts = spec.getExportAttributes()
    if scope.export_atts is not None:
        att_list = scope.export_atts.findAttributes('ExportSpec')
    if len(att_list) > 1:
        msg = 'More than one ExportSpec instance -- ignoring all'
        print 'WARNING:', msg
        scope.logger.addWarning(msg)
        return False
    export_spec_att = att_list[0]

    # Initialize solver list
    solver_item = export_spec_att.findString('Analysis')
    if solver_item is None:
        msg = 'Missing \"Analysis\" item -- cannot export'
        scope.logger.addError(msg)
        raise Exception(msg)
    if not solver_item.isSet(0):
        msg = 'Analysis item is not set -- cannot export'
        scope.logger.addError(msg)
        raise Exception(msg)
    solver_string = solver_item.value(0)
    #print 'solver_string:', solver_string
    scope.solver_list = solver_string.split('.')

    # Get output filename (path)
    output_path = None
    file_item = export_spec_att.findFile('OutputFile')
    if file_item is not None:
        output_path = file_item.value(0)
    if not output_path:
        raise Exception('No output file specified')
    scope.output_path = output_path

    reload(pyarc_writer)
    writer = pyarc_writer.PyARCWriter()
    success = writer.write(scope)

    if success:
        print 'Successfully wrote', scope.output_path
    return success
