/*
	Copyright (c) 2024 PTC Inc. and/or Its Subsidiary Companies. All Rights Reserved.
*/


#include <ProToolkit.h>
#include <ProMdl.h>
#include <ProModelitem.h>
#include <ProGeomitem.h>
#include <ProCsys.h>
#include <ProSolid.h>

#include <UtilString.h>

/*--------------------------------------------------------------------*\
ProAppData used while visiting Csys
\*--------------------------------------------------------------------*/
typedef struct {
	ProMdl		model;
	ProCsys		p_csys;
	ProName		csys_name;
	}UserCsysAppData ; 
/*--------------------------------------------------------------------*\
Filter function used while visiting Csys
\*--------------------------------------------------------------------*/
ProError CsysFindFilterAction (
	ProCsys		this_csys,
	ProAppData	app_data)
{
  int 		status;
  ProName	this_csys_name;
  ProModelitem mdlitem;
  int id;

  status = ProCsysIdGet (this_csys, &id);
  status = ProModelitemInit(((UserCsysAppData *) app_data)->model, id, PRO_CSYS, &mdlitem);
  status = ProModelitemNameGet ( &mdlitem, this_csys_name);
  if (status != PRO_TK_NO_ERROR)
	return(status);

  if (ProUtilWstrcmp( ((UserCsysAppData *) app_data)->csys_name, this_csys_name) == 0)
    return(PRO_TK_NO_ERROR);
  return(PRO_TK_CONTINUE);
}  

/*--------------------------------------------------------------------*\
Visit Action used while visiting Csys
\*--------------------------------------------------------------------*/
ProError CsysFindVisitAction (
	ProCsys		this_csys,
	ProError	filter_return,
        ProAppData      app_data)
{
  int 		status;
 
  if (filter_return != PRO_TK_NO_ERROR)
	return (filter_return);
  
   ( (UserCsysAppData *) app_data) -> p_csys = this_csys; 
  return (PRO_TK_USER_ABORT);
}

/*====================================================================*\
    FUNCTION :  ProUtilCsysFind()
    PURPOSE  :  Find a csys given a model and a csys name
\*====================================================================*/
ProError ProUtilCsysFind(
	ProMdl		p_model,	/* IN  - the model in which to look */
	ProName		csys_name,	/* IN  - the name of the csys to find */
	ProCsys		*p_csys)	/* OUT - the csys handle */
{
  int 			status;
  ProMdlType		mdl_type;
  UserCsysAppData	app_data;
 
  status = ProMdlTypeGet ( p_model, &mdl_type);
  if (status != PRO_TK_NO_ERROR) 
	return(status);

  if ((mdl_type != PRO_MDL_PART) && (mdl_type != PRO_MDL_ASSEMBLY))
	return(PRO_TK_INVALID_TYPE);

  ProUtilWstrcpy (app_data.csys_name, csys_name);
  app_data.model = p_model;

  status = ProSolidCsysVisit( 	(ProSolid) p_model, 
				(ProCsysVisitAction) CsysFindVisitAction,
				(ProCsysFilterAction) CsysFindFilterAction,
				(ProAppData) &app_data);
  if (status != PRO_TK_USER_ABORT) 
	return(PRO_TK_E_NOT_FOUND);
  *p_csys = app_data.p_csys;

  return (PRO_TK_NO_ERROR);
}