package com.ibm.urbancode.zos.common;
/*
 * Licensed Materials - Property of IBM Corp.
 * IBM UrbanCode Build
 * IBM UrbanCode Deploy
 * IBM UrbanCode Release
 * IBM AnthillPro
 * (c) Copyright IBM Corporation 2002, 2015. All Rights Reserved.
 *
 * U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by
 * GSA ADP Schedule Contract with IBM Corp.
 */
 
import com.ibm.jzos.*;
import java.util.regex.Pattern
public class DataSetHelper {
	public static Map<String,String> searchNonVsamDataset(String pattern,int max=-1){
		CatalogSearch catSearch = new CatalogSearch(pattern);
		catSearch.setEntryTypes(new String("A"));
		catSearch.addFieldName("ENTNAME");
		catSearch.addFieldName("VOLSER");
		catSearch.search();
		def Map<String,String> result = [:];
		while(catSearch.hasNext()){
			CatalogSearch.Entry entry=catSearch.next();
			if(entry.isDatasetEntry()){
				CatalogSearchField datasetName = entry.getField("ENTNAME")
				CatalogSearchField volume = entry.getField("VOLSER");
				if(max<0||(max>0&&result.size()<=max)){
					result.put(datasetName.getFString().trim(), volume.getFString().trim());
				}else{
					break;
				}
			}
		}
		return result;
	}
	
	//get PDS members based on the member pattern
	//return the data set name if it is sequential
	public static List<String> getMemebers(String datasetName, String volume, String memberPattern){
		def List<String> result=[];

		Format1DSCB dscb = ZFile.obtainDSN(getSlashSlashQuotedDSN(datasetName), volume);
		if(dscb.getDS1DSORG() == Format1DSCB.DS1DSGPS){
			//DSORG = PS
			result.add(getSlashSlashQuotedDSN(datasetName));
		}else if (dscb.getDS1DSORG() == Format1DSCB.DS1DSGPO){
			//DSORG = PO
			if(memberPattern?.trim()){
				def PdsDirectory pds = new PdsDirectory(getSlashSlashQuotedDSN(datasetName))
				def Iterator iterator=pds.iterator();
				while(iterator.hasNext()){
					PdsDirectory.MemberInfo member = iterator.next();
					def memberName = member.getName();
					def pattern = memberPattern.replaceAll('\\.',"\\\\.")
					pattern = pattern.replaceAll("\\\$","\\\$");
					pattern = pattern.replaceAll('\\*',".*")
					if(memberName.matches(pattern)){
						result.add(getSlashSlashQuotedDSN("$datasetName($memberName)"));
					}
				}
				pds.close();
			}
		}
		return result;
	}

	public static String getSlashSlashQuotedDSN(String datasetName){
		return ZFile.getSlashSlashQuotedDSN(datasetName,true);
	}
	
}
