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


#include <ProToolkit.h>
#include <ProDrawing.h>
#include <ProFaminstance.h>
#include <PTApplsUnicodeUtils.h>

/*==================================================================*\
FUNCTION: UserDrawingSolidReplace()
PURPOSE:  Replaces all instance solid models in a drawing with their
           generic.  Similar to the Pro/ENGINEER behavior,  the function 
	   will not replace models if the target generic model is already 
	   present in the drawing.
\*==================================================================*/
int UsrDrawingSolidReplace()
{
  ProError      err;
  ProDrawing    drawing;
  ProMdlType    mdl_type;
  ProSolid*     solid_array;
  int           array_size, i;
  ProSolid      generic;
  
/*------------------------------------------------------------------*\
  Use the current model to create the drawing.
\*------------------------------------------------------------------*/
  err = ProMdlCurrentGet ((ProMdl*)&drawing); 
  if (err != PRO_TK_NO_ERROR)
      return (err);
  err = ProMdlTypeGet ((ProMdl)drawing, &mdl_type);
  if (err != PRO_TK_NO_ERROR || 
      (mdl_type != PRO_MDL_DRAWING))
       return PRO_TK_INVALID_TYPE;

/*------------------------------------------------------------------*\
  Visit the drawing models.
\*------------------------------------------------------------------*/
  err = ProDrawingSolidsCollect (drawing, &solid_array);
  if (err != PRO_TK_NO_ERROR)
    return (err);

  ProArraySizeGet (solid_array, &array_size);

/*------------------------------------------------------------------*\
  Loop on all of the drawing models.
\*------------------------------------------------------------------*/  
  for (i = 0; i < array_size; i++)
    {
/*------------------------------------------------------------------*\
      If the generic is not an instance, continue.
\*------------------------------------------------------------------*/ 
      err = ProFaminstanceGenericGet ((ProMdl)solid_array[i], 
				      PRO_B_TRUE, 
				      (ProMdl*)&generic);
  
      if (err != PRO_TK_NO_ERROR)
	continue;

/*------------------------------------------------------------------*\
      Replace all instances with their (top-level) generic.
\*------------------------------------------------------------------*/
      err = ProDrawingSolidReplace (drawing, solid_array[i], generic, 
			      PRO_B_TRUE); 
      if (err == PRO_TK_E_FOUND)
	{
	  ProTKPrintf ("Model was not replaced because");
	  ProTKPrintf (" the target model is already in the drawing.\n");
	}
    }
  
  return (PRO_TK_NO_ERROR);
}