/* Copyright (c) 2009, Oracle and/or its affiliates. All rights reserved. */

public class DICOMSqlTemplates {
	/* Generate SQL statement to get all records from the DICOM table. */
	private String generateAllSql(String table) {
		String queryAll = "select * from " + table + " for update";
		return queryAll;
	}

	/* 
	 * With given attribute's name and value, generate corresponding SQL
	 * statement to get DICOM record with the given value on the specified 
	 * attribute.
	 */
	private String generateSelectedSql(
	    String attName, String attValue, String table) {
		String subTable = "select id as \"IDENTIFIER\" from " + 
		    table + " t " + "where ";
		String queryMetadataPre = 
		    "extractValue(t.dicom.metadata, \'/DICOM_OBJECT/*[@name=";
		String queryMetadataSuf = 
"\', \'xmlns=http://xmlns.oracle.com/ord/dicom/metadata_1_0\')";
		String querySql = 
"select * from " + table + " t " + "where t.id=";
		
		/*
		 * Generate SQL statement that selects ID of all DICOMs that 
		 * have the given value on the specified attribute. To select 
		 * matching DICOMs, extract all values on the attribute from 
		 * XML metadata document and judge if it is the same as we 
		 * expected. 
		 */
		subTable += queryMetadataPre;
		if (attName == "PATIENT_NAME")
			subTable += "\"Patient\'\'s Name\"]/VALUE";
		else if (attName.equals("MODALITY"))
			subTable += "\"Modality\"]";
		subTable += queryMetadataSuf;
		subTable += "=" + "\'" + attValue + "\'";
		
		/* 
		 * Generate SQL statement that select DICOMs, their thumbnails
		 * whose ID are returned in the above subTable.
		 */
		querySql += "(" + subTable + ") for update"; 
		return querySql;	
	}
	
	/*
	 * Find SQL template for the request with regards to its request scope, 
	 * that is if it wants all or some DICOMs in the table, and generate 
	 * corresponding SQL statement.
	 */
	private String generateSqlQuery(String request, String table) {
		String[] attribute;
		
		if (request.equals("All"))
			return generateAllSql(table);
		else {
			/* 
			 * Get attribute's name and value from the request. 
			 * The format of any request except "ALL" is the 
			 * combination of attribute value and name linked 
			 * with '@'. 
			 */
			attribute = request.split("@");
			return generateSelectedSql(attribute[0], attribute[1],
			    table);
		}
	}
	
	/*
	 * Get SQL statement of a given type for request in the table. The type
	 * indicates which kind of SQL statement it is. 
	 */
	public String getSqlStatement(String type, String request, 
	    String table) {
		String statement = null;
		
		if (request == null || table == null)
			throw new NullPointerException();
		
		if (type == "GET")
			statement = generateSqlQuery(request, table);
		
		System.out.println("[LOG] Execute " + statement);
		return statement;
	}
}
