
package ext;

import java.util.*;
import java.rmi.RemoteException;
import java.io.*;

import wt.util.*;
import wt.fc.*;
import wt.vc.*;
import wt.vc.wip.*;
import wt.vc.config.*;

import wt.query.*;
import wt.epm.*;
import wt.epm.build.*;
import wt.epm.structure.*;
import wt.enterprise.RevisionControlled;

import wt.part.*;
import wt.folder.*;
import wt.lifecycle.*;
import wt.lifecycle.State;
import wt.inf.container.*;

import wt.httpgw.GatewayAuthenticator;
import wt.method.RemoteMethodServer;
import com.ptc.windchill.cadx.common.util.AssociateUtilities;
import com.ptc.windchill.cadx.common.util.GenericUtilities;
import com.ptc.windchill.cadx.common.util.ObjectDependencyUtility;

public class epmList_30 {

	public static void FindEpmNo(String QueType, String objNo) throws WTException, WTPropertyVetoException {

		configSpec = new LatestConfigSpec();

		QuerySpec qs = new QuerySpec(EPMDocument.class);
		qs.appendWhere(new SearchCondition(EPMDocument.class,EPMDocument.NUMBER,SearchCondition.LIKE,objNo));
		qs.appendAnd();
		qs.appendWhere(new SearchCondition(EPMDocument.class, "iterationInfo.latest", "TRUE"));

		qs = configSpec.appendSearchCriteria(qs);
		qr = PersistenceHelper.manager.find(qs);
		qr = configSpec.process(qr);

		while (qr.hasMoreElements()) {
			epm = (EPMDocument)qr.nextElement();
			epmm = (EPMDocumentMaster)epm.getMaster();

			epmNo = epm.getNumber();
			epmCont = epm.getContainer();
			epmFolder = wt.folder.FolderHelper.getFolder(epm);

			LMObject = (LifeCycleManaged)epm;
			StStg = (String)LMObject.getLifeCycleState().toString();

			System.out.println( "Running Tree For EPMDocument Number: "+epmNo+"\n");
			epmTree(QueType,epm);
		}
	}

	public static void epmTree(String QueTypeIN, EPMDocument epmDoc)
		throws WTException
	{
		try{
			arraylistTop = new ArrayList();
			arraylist1 = new ArrayList();

			configSpec = new LatestConfigSpec();

			qrChildChecker = EPMStructureHelper.service.navigateUsesToIteration(epmDoc, null, false, configSpec);

			if ( qrChildChecker.size() > 0) {
				arraylistTop.add(epmDoc);

				arraylist1 = new ArrayList();
				arraylist1 = listSortedChildrenInfo(epmDoc, configSpec);

				for (int x = 0; x < arraylistTop.size(); x++ ) {
					EPMDocument epmTop = (EPMDocument)arraylistTop.get(x);
					epmCont = epmTop.getContainer();
					epmFolder = wt.folder.FolderHelper.getFolder(epmTop);

					LMObject = (LifeCycleManaged)epmTop;
					StStg = (String)LMObject.getLifeCycleState().toString();

					System.out.println( "EPMDoc Number: "+ epmTop.getNumber() + "| EPMDoc Name: " + epmTop.getName());
					System.out.println( "EPMDoc CADName: "+ epmTop.getCADName() + "| EPMDoc DocType: " + epmTop.getDocType());
					System.out.println( "EPMDoc Container: "+ epmCont.getName() + "| EPMDoc Folder: " + epmFolder);
					System.out.println( "EPMDoc Version: " + epmTop.getVersionIdentifier().getValue() + "."+epmTop.getIterationIdentifier().getValue()+"| LC State: "+StStg+"\n");

					getWtpAssoc(QueTypeIN,epmTop,epmFolder);
				}
			}
		}
		catch(Exception exception) { exception.printStackTrace(); }
	}

	public static void getWtpAssoc(String QueTypeIN, EPMDocument epmIN, Folder epmFolderIN)
		throws WTException
	{
		//wtpAssoc = AssociateUtilities.getActiveAssociatedPart((EPMDocument)epmIN);

		WTPart wtpList[]  = ObjectDependencyUtility.getAssociated((EPMDocument)epmIN);
		//System.out.println( "\tAssociated WTPart length: " + wtpList.length+"\n");

		if( wtpList != null ) {
			for (int y = 0; y < wtpList.length; y++ ) {
				WTPart wtpAssoc = (WTPart)wtpList[y];
				wtpNo = wtpAssoc.getNumber();
				wtpCont = wtpAssoc.getContainer();
				wtpFolder = wt.folder.FolderHelper.getFolder(wtpAssoc);

				epmNoIN = "";
				epmNoIN = epmIN.getNumber();

				LMObject = (LifeCycleManaged)wtpAssoc;
				StStg = (String)LMObject.getLifeCycleState().toString();

				System.out.println( "\tAssociated WTPart Info: ");
				System.out.println( "\tWTPart Number: "+ wtpAssoc.getNumber() + "| WTPart Name: " + wtpAssoc.getName());
				System.out.println( "\tWTPart Container: "+ wtpCont.getName() + "| WTPart Folder: " + wtpFolder);
				System.out.println( "\tWTPart Version: " + wtpAssoc.getVersionIdentifier().getValue() + "."+wtpAssoc.getIterationIdentifier().getValue()+"| Life Cycle State: "+StStg+"\n");

				if (wtpNo.indexOf(".") > 0 && wtpNo != null ) {
					System.out.println( "\tOrig WTPart String Number: "+wtpNo);
					wtpNo = removeExt(wtpNo);
					System.out.println( "\tFinal WTPart String Number: "+wtpNo+"\n");
				}

				if (epmNoIN.indexOf(".") > 0 && epmNoIN != null ) {
					System.out.println( "\tOrig EPMDoc String Number: "+epmNoIN);
					epmNoIN = removeExt(epmNoIN);
					System.out.println( "\tFinal EPMDoc String Number: "+epmNoIN+"\n");
				}

				if (wtpNo.equals(epmNoIN)) {
					System.out.println( "\tEPMDoc: "+epmNoIN+" & WTPart "+ wtpNo + " Numbers DO Match: \n");
				}
				else {
					System.out.println( "\tEPMDoc: "+epmNoIN+" & WTPart "+ wtpNo + " Numbers DO NOT Match: \n");

					WTPartMaster wtpMaster = (WTPartMaster)wtpAssoc.getMaster();

					System.out.println((new StringBuilder()).append("\tFound WTPart Master of ").append(wtpMaster.getNumber()).toString()+"\n");

					if (QueTypeIN.equals("-rw")) {
						try
						{
							if (epmNoIN.indexOf(".") > 0 && epmNoIN != null ) {
								System.out.println( "\tOrig EPMDoc String Number: "+epmNoIN);
								epmNoIN = removeExt(epmNoIN);
								System.out.println( "\tFinal EPMDoc String Number: "+epmNoIN+"\n");
							}

							WTPart newWtp2 = FindWtpNoWTP(epmNoIN);

							if (newWtp2 != null) {
								//epmNoIN = epmNoIN+"_wtp";
								epmNoIN = epmIN.getNumber();
							}

							wt.fc.IdentificationObject idObj = wtpMaster.getIdentificationObject();
							WTPartMasterIdentity wtpmID = (WTPartMasterIdentity)idObj;
							wtpmID.setNumber(epmNoIN);
							IdentityHelper.service.changeIdentity(wtpMaster, wtpmID);
							System.out.println("\tIdentity Changed to: "+epmNoIN+"\n");
						}
						catch(WTException wte)
						{
							System.out.println( "\tWTPart Number Change Failure:\n");
							wte.printStackTrace();
						}
						catch(WTPropertyVetoException wtp)
						{
							System.out.println( "\tWTPart Number Change Failure:\n");
							wtp.printStackTrace();
						}
					}
				}
			}
		}
		else {
			System.out.println( "\tNO Associated WTPart: \n");

			epmNoIN = "";
			epmNoIN = epmIN.getNumber();

			try
			{
				if (epmNoIN.indexOf(".") > 0 && epmNoIN != null ) {
					System.out.println( "\tOrig EPMDoc String Number: "+epmNoIN);
					epmNoIN = removeExt(epmNoIN);
					System.out.println( "\tFinal EPMDoc String Number: "+epmNoIN+"\n");
				}

				WTPart newWtp1 = FindWtpNoWTP(epmNoIN);

				if (newWtp1 != null) {
					System.out.println( "\tFound Non Associated WTPart NO: "+newWtp1.getNumber() +"\n\twith same Number as EPMDoc: "+epmNoIN+"\n");

					if (QueTypeIN.equals("-rw")) {

						newWtp1 = (WTPart)setCheckoutInfo(newWtp1, WorkInProgressState.WORKING);
						EPMBuildRule epmbuildrule = EPMBuildRule.newEPMBuildRule(epmIN, newWtp1);
						epmbuildrule = (EPMBuildRule)PersistenceHelper.manager.save(epmbuildrule);

						System.out.println( "\tCreated Association between WTPart Number: "+newWtp1.getNumber()+ "| EPMDoc Number: "+epmIN.getNumber()+"\n");
					}
				}
				else
				{
					if (QueTypeIN.equals("-rw")) {

						// Create and persist new wtpart
						epmNoIN2 = epmIN.getNumber();
						epmNmIN2 = epmIN.getName();

						epmNoIN2 = removeExt(epmNoIN2);
						epmNmIN2 = removeExt(epmNmIN2);

						WTPart newWtp = WTPart.newWTPart(epmNoIN2,epmNmIN2);
						FolderHelper.assignLocation(newWtp,epmFolderIN);
						newWtp=(WTPart)PersistenceHelper.manager.save(newWtp);

						System.out.println( "\tCreated WTPart Number: "+newWtp.getNumber());

						newWtp = (WTPart)setCheckoutInfo(newWtp, WorkInProgressState.WORKING);
						EPMBuildRule epmbuildrule = EPMBuildRule.newEPMBuildRule(epmIN, newWtp);
						epmbuildrule = (EPMBuildRule)PersistenceHelper.manager.save(epmbuildrule);

						System.out.println( "\tCreated Association between WTPart: "+newWtp.getNumber()+ " & EPMDoc: "+epmIN.getNumber()+"\n");
					}
				}
			}
			catch(Exception exception) { exception.printStackTrace(); }
		}
	}

	public static void FindWtpNo(String QueType, String objNo) throws WTException, WTPropertyVetoException {
		configSpec = new LatestConfigSpec();

		QuerySpec qs = new QuerySpec(WTPart.class);
		qs.appendWhere(new SearchCondition(WTPart.class,WTPart.NUMBER,SearchCondition.LIKE,objNo));
		qs.appendAnd();
		qs.appendWhere(new SearchCondition(WTPart.class, "iterationInfo.latest", "TRUE"));

		qs = configSpec.appendSearchCriteria(qs);
		qr = PersistenceHelper.manager.find(qs);
		qr = configSpec.process(qr);

		while (qr.hasMoreElements()) {
			wtpOrig = (WTPart)qr.nextElement();
			System.out.println( "Running Original WTPart Tree\n");
			wtpTree(wtpOrig);
		}
	}

	public static WTPart FindWtpNoWTP(String objNo) throws WTException, WTPropertyVetoException {

		configSpec = new LatestConfigSpec();

		QuerySpec qs = new QuerySpec(WTPart.class);
		qs.appendWhere(new SearchCondition(WTPart.class,WTPart.NUMBER,SearchCondition.EQUAL,objNo));
		qs.appendAnd();
		qs.appendWhere(new SearchCondition(WTPart.class, "iterationInfo.latest", "TRUE"));

		qs = configSpec.appendSearchCriteria(qs);
		qr = PersistenceHelper.manager.find(qs);
		qr = configSpec.process(qr);

		while (qr.hasMoreElements()) { wtpOrig = (WTPart)qr.nextElement(); }

		return wtpOrig;
	}

	public static void wtpTree(WTPart wtp)
		throws WTException
	{
		try{
			arraylistTop = new ArrayList();
			arraylist1 = new ArrayList();

			configSpec = new LatestConfigSpec();

			qrChildChecker = WTPartHelper.service.getUsesWTParts(wtp, configSpec);

			if ( qrChildChecker.size() > 0) {
				arraylistTop.add(wtp);

				arraylist1 = new ArrayList();
				arraylist1 = listSortedChildrenInfo(wtp, configSpec);

				for (int x = 0; x < arraylistTop.size(); x++ ) {
					WTPart wtpTop = (WTPart)arraylistTop.get(x);
					wtpCont = wtpTop.getContainer();
					wtpFolder = wt.folder.FolderHelper.getFolder(wtpTop);

					LMObject = (LifeCycleManaged)wtpTop;
					StStg = (String)LMObject.getLifeCycleState().toString();

					System.out.println( "WTPart Number: "+ wtpTop.getNumber() + "| WTPart Name: " + wtpTop.getName());
					System.out.println( "WTPart Container: "+ wtpCont.getName() + "| WTPart Folder: " + wtpFolder);
					System.out.println( "WTPart Version: " + wtpTop.getVersionIdentifier().getValue() + "."+wtpTop.getIterationIdentifier().getValue()+"| LC State: "+StStg+"\n");

					EPMDocument epmList[] = ObjectDependencyUtility.getAssociated((WTPart)wtpTop);
					//System.out.println( "\tAssociated EPMDoc length: " + epmList.length+"\n");

					if( epmList != null ) {
						for (int y = 0; y < epmList.length; y++ ) {
							EPMDocument epmTop = (EPMDocument)epmList[y];
							epmCont = epmTop.getContainer();
							epmFolder = wt.folder.FolderHelper.getFolder(epmTop);

							LMObject = (LifeCycleManaged)epmTop;
							StStg = (String)LMObject.getLifeCycleState().toString();

							System.out.println( "\tAssociated EPMDoc Info: ");
							System.out.println( "\tEPMDoc Number: "+ epmTop.getNumber() + "| EPMDoc Name: " + epmTop.getName());
							System.out.println( "\tEPMDoc CADName: "+ epmTop.getCADName() + "| EPMDoc DocType: " + epmTop.getDocType());
							System.out.println( "\tEPMDoc Container: "+ epmCont.getName() + "| EPMDoc Folder: " + epmFolder);
							System.out.println( "\tEPMDoc Version: " + epmTop.getVersionIdentifier().getValue() + "."+epmTop.getIterationIdentifier().getValue()+"| LC State: "+StStg+"\n");

							//getWtpAssoc(QueTypeIN,epmTop,epmFolder);
						}
					}
				}
			}
		}
		catch(Exception exception) { exception.printStackTrace(); }
	}

	public static Persistable[][] my_getUsesWTParts(WTPart wtpart, ConfigSpec configSpec)
		throws WTException
	{
		ArrayList arraylist2 = new ArrayList();
		QueryResult qrMY = WTPartHelper.service.getUsesWTParts(wtpart, configSpec);
		do
		{
			if(!qrMY.hasMoreElements())
	 			break;
			Persistable apersistable[] = (Persistable[])(Persistable[])qrMY.nextElement();
			if(apersistable[1] instanceof WTPart)
			{
				WTPartUsageLink wtpartusagelink = (WTPartUsageLink)apersistable[0];
	 			if(!wtpartusagelink.dissatisfiesFilterCriteria())
				arraylist2.add(apersistable);

				WTPart wtChild3 = ((WTPart) apersistable[1] );
				arraylistTop.add(wtChild3);
			}
		} while(true);
		return (Persistable[][])(Persistable[][])arraylist2.toArray(new Persistable[arraylist2.size()][]);
	}

	public static Persistable[][] my_getUsesEPMDocs(EPMDocument epmDoc, ConfigSpec configSpec)
		throws WTException
	{
		ArrayList arraylist2 = new ArrayList();
		QueryResult qrMY = EPMStructureHelper.service.navigateUsesToIteration(epmDoc, null, false, configSpec);
		do
		{
			if(!qrMY.hasMoreElements())
	 			break;

			Persistable apersistable[] = (Persistable[])(Persistable[])qrMY.nextElement();
			Persistable persistable = apersistable[0];
			Persistable persistable1 = apersistable[1];

			if((persistable instanceof EPMDependencyLink) && (persistable1 instanceof EPMDocument))
			{
				EPMDependencyLink epmdependencylink = (EPMDependencyLink)persistable;
				epm1 = (EPMDocument)persistable1;
				epmCont = epm1.getContainer();
				epmFolder = wt.folder.FolderHelper.getFolder(epm1);
				epmNo = epm1.getNumber();

				arraylist2.add(apersistable);
				arraylistTop.add(epm1);

				LMObject = (LifeCycleManaged)epm1;
				StStg = (String)LMObject.getLifeCycleState().toString();
			}
		} while(true);
		return (Persistable[][])(Persistable[][])arraylist2.toArray(new Persistable[arraylist2.size()][]);
	}

	public static ArrayList listSortedChildrenInfo(WTPart wtpart, ConfigSpec configSpec)
		throws WTPropertyVetoException, WTException
	{
		ArrayList arraylist = new ArrayList();
		Persistable apersistable[][] = my_getUsesWTParts(wtpart, configSpec);
		if(apersistable.length > 0)
		{
			for(int j = 0; j < apersistable.length; j++)
			{
				WTPart wtChild2 = (WTPart)apersistable[j][1];
				ArrayList arraylist1 = listSortedChildrenInfo(wtChild2, configSpec);
				arraylist.add(arraylist1);
			}
		}
		return arraylist;
	}

	public static ArrayList listSortedChildrenInfo(EPMDocument epmDoc, ConfigSpec configSpec)
		throws WTPropertyVetoException, WTException
	{
		ArrayList arraylist = new ArrayList();
		Persistable apersistable[][] = my_getUsesEPMDocs(epmDoc, configSpec);
		if(apersistable.length > 0)
		{
			for(int j = 0; j < apersistable.length; j++)
			{
				EPMDocument epmDoc2 = (EPMDocument)apersistable[j][1];
				ArrayList arraylist1 = listSortedChildrenInfo(epmDoc2, configSpec);
				arraylist.add(arraylist1);
			}
		}
		return arraylist;
	}

	public static String removeExt(String tmpStg) {
		if ( tmpStg.endsWith(".PRT") || tmpStg.endsWith(".prt") ) { tmpStg = tmpStg.substring(0, tmpStg.length() - 4); }
		if ( tmpStg.endsWith(".DRW") || tmpStg.endsWith(".drw") ) { tmpStg = tmpStg.substring(0, tmpStg.length() - 4); }
		if ( tmpStg.endsWith(".ASM") || tmpStg.endsWith(".asm") ) { tmpStg = tmpStg.substring(0, tmpStg.length() - 4); }

		return tmpStg;
	}

	protected static RevisionControlled setCheckoutInfo(RevisionControlled revisioncontrolled, WorkInProgressState workinprogressstate)
		throws WTException
	{
		try
		{
			CheckoutInfo checkoutinfo = CheckoutInfo.newCheckoutInfo();
			checkoutinfo.setState(workinprogressstate);
			revisioncontrolled.setCheckoutInfo(checkoutinfo);
		}
		catch(WTPropertyVetoException wtp) { wtp.printStackTrace(); }
		catch(WTException wte) { wte.printStackTrace(); }
		return revisioncontrolled;
	}

	public static void main(String[] args) {
		RemoteMethodServer rms = RemoteMethodServer.getDefault();
		GatewayAuthenticator auth = new GatewayAuthenticator();
		auth.setRemoteUser("wcadmin");
		rms.setAuthenticator(auth);

		try {
			if(args.length < 2)
			{
				System.out.println(Usage);
				System.exit(0);
			}
			else {
				OT = args[0];
				QueStg = args[1].toUpperCase();

				if ( OT.equals("-qe")||OT.equals("-rw") ) {
					FindEpmNo(OT,QueStg);
				}
				else if ( OT.equals("-qw") ) {
					FindWtpNo(OT,QueStg);
				}
				else { System.out.println(Usage); }

				System.exit(0);
			}
		}
		catch (WTException wtee) { wtee.printStackTrace(); }
		catch (WTPropertyVetoException wtpe) { wtpe.printStackTrace(); }
		finally { System.exit(0); }
	}

	public static String Usage = "\nUsage:\n\njava/windchill [-mx1024m] "+
	"ext.epmList -<query/rename> %<epmdoc/wtpart number search string>%\n\n"+
	"1st Argument = <query/rename>:\n\n-qe = query epmdocs only\n-qw = query wtparts only\n"+
	"-rw = query epmdocs & rename wtparts (query 1st)\n\n"+
	"1st Argument should be lower case.\n\n2nd Argument = %<object number string>%\n\n"+
	"Should include % where % = * = wild card.\n";

	static String OT, QueStg, StStg, epmNo, wtpNo, epmNoIN, epmNoIN2, epmNmIN2;
	static WTContainer wtpCont, epmCont;
	static Folder wtpFolder, epmFolder;
	static EPMDocumentMaster epmm;
	static EPMDocument epm, epm1, epmOrig;
	static WTPart wtpAssoc, wtpOrig;
	static LifeCycleTemplate lifecycletemplate;
	static LifeCycleManaged LMObject;
	static QueryResult qrUses, qrChildChecker, qr;
	static ArrayList arraylist1, arraylistTop;
	static ConfigSpec configSpec;
}

