/*******************************************************************************
 *  Copyright 2017-2018 Centre for Development of Advanced Computing(C-DAC), Pune
 *  
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *  
 *   http://www.apache.org/licenses/LICENSE-2.0
 *  
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *******************************************************************************/
package cdac.medinfo.sdk.dcm30_04.testscu.securityprofiles.onlineelectronicstoragesecureuse;
import cdac.medinfo.sdk.dcm30_04.utils.DicomConstants;




import java.io.File;
import java.io.IOException;
import java.util.Locale;

import cdac.medinfo.sdk.dcm30_04.commoninterface.IDataElement;
import cdac.medinfo.sdk.dcm30_04.commoninterface.IDataSet;
import cdac.medinfo.sdk.dcm30_04.commoninterface.IItem;
import cdac.medinfo.sdk.dcm30_04.dicommodel.xray.XRayAngiographicIOD;
import cdac.medinfo.sdk.dcm30_04.dicomparserserializers.DicomSerializer;
import cdac.medinfo.sdk.dcm30_04.dicomstreams.DicomBufferStream;
import cdac.medinfo.sdk.dcm30_04.enums.EnumSOPClassUIDs;
import cdac.medinfo.sdk.dcm30_04.exceptions.InvalidIODException;
import cdac.medinfo.sdk.dcm30_04.exceptions.SerializeException;
import cdac.medinfo.sdk.dcm30_04.services.dicomnetcommons.EnumImplOpsStatus;
import cdac.medinfo.sdk.dcm30_04.services.dicomnetcommons.SinkException;
import cdac.medinfo.sdk.dcm30_04.services.dimsecommons.DicomMessage;
import cdac.medinfo.sdk.dcm30_04.services.dimsecommons.IDataSink;
import cdac.medinfo.sdk.dcm30_04.services.dimsecommons.IQueryModel;
import cdac.medinfo.sdk.dcm30_04.services.onlineelectronicstoragesecureuse.OnlineElectronicStorageSecureUseProfile;
import cdac.medinfo.sdk.dcm30_04.utils.DicomConfig;
import cdac.medinfo.sdk.dcm30_04.utils.DicomLogger;
import cdac.medinfo.sdk.dcm30_04.utils.ICollectionIterator;
import cdac.medinfo.sdk.dcm30_04.utils.IPairedCollection;
import cdac.medinfo.sdk.dcm30_04.utils.ISingleCollection;
import cdac.medinfo.sdk.dcm30_04.utils.ResourceBundleWrapper;
import cdac.medinfo.sdk.dcm30_04.utils.StandardMethods;


/**
 * StorageCommitmentSinkImpl is the default implementation for DataSink implementation for Storage Commitment.
 * This implementation provides the storage of Data Sets
 * for which Storage Commitment request is received.
 */
public class StorageCommitmentSinkImpl implements IDataSink
{
	private IPairedCollection<String , String> objSopInstanceFilePathCollection;
	private IPairedCollection<String , String> objSopInstanceSopClassCollection;
	
	private String strStoragePath = "C:/Test/";

	public IPairedCollection<String, String> getSopInstanceFilePathCollection() {
		return objSopInstanceFilePathCollection;
	}

	public void setSopInstanceFilePathCollection(
			IPairedCollection<String, String> objSopInstanceFilePathCollection) {
		this.objSopInstanceFilePathCollection = objSopInstanceFilePathCollection;
	}

	public IPairedCollection<String, String> getSopInstanceSopClassCollectio() {
		return objSopInstanceSopClassCollection;
	}

	public void setSopInstanceSopClassCollectio(
			IPairedCollection<String, String> objSopInstanceSopClassCollectio) {
		this.objSopInstanceSopClassCollection = objSopInstanceSopClassCollectio;
	}

	private IDataSet getDataSet(String strFilePath,String strSopClassUID) throws InvalidIODException, IOException
	{
		EnumSOPClassUIDs enumSOPClassUID = StandardMethods.getSOPClassUID(strSopClassUID);
		IDataSet objIDataSet = null;
		if(enumSOPClassUID!=null)
		{
			switch(enumSOPClassUID)
			{
			case XRAYANGIOGRAPHICIOD:
				XRayAngiographicIOD objXRayAngiographicIOD = new XRayAngiographicIOD(strFilePath);
				objIDataSet = objXRayAngiographicIOD.getDataSet();
				break; 

			}
		}
		return objIDataSet;
	}

	private void  store(String strFilePath,String strSopClassUID,String strStoragePath) throws InvalidIODException, IOException
	{
		File objDir = new File(strStoragePath);
		objDir.mkdirs();
		IDataSet objIDataSet = getDataSet(strFilePath, strSopClassUID);
		OnlineElectronicStorageSecureUseProfile objSecureUseProfile =  OnlineElectronicStorageSecureUseProfile.getOnlineElectronicStorageSecureUseProfile();
		//		 Finalising the dataset
		objSecureUseProfile.finalise(objIDataSet);
		String strSOPInstanceUID = (String)objIDataSet.getValue(0x0008, 0x0018);
		if(strStoragePath.endsWith("/") == true)
			strStoragePath = strStoragePath.concat(strSOPInstanceUID);
		else
			strStoragePath = strStoragePath.concat("/").concat(strSOPInstanceUID);

		DicomSerializer objDicomSerializer = new DicomSerializer();
		objDicomSerializer.serializeAsPart10File(strStoragePath,objIDataSet,null,objIDataSet.getDictionaryReader(),true);

		System.out.println("Confirmation peration done for "+strSOPInstanceUID);

	}


	/**
	 * This function Stores the DataSet at the Storage Path Specified by the user.
	 * @param objDicomMessage instance od Dicom Message Containing DataSet for which
	 * storage commitment has to be provided.
	 * @param strStoragePath String value of Storage Path where the Data Set are stored
	 * for which storage commitment is provided.
	 * @return short - shows status value which will be used in generation of response
	 * 					Refer EnumImplOpsStatus for suppported response status values.
	 */
	@SuppressWarnings("unchecked")
	public short store(DicomMessage objDicomMessage, String strStoragePath)throws SinkException
	{
		try
		{
			strStoragePath = this.strStoragePath;
			System.out.println("Default Storage path = "+strStoragePath);
			IDataSet objIDataSet = objDicomMessage.getDataSet();
			ISingleCollection<IItem> objSQReferencedSOPSequenceItem = (ISingleCollection<IItem>)(objIDataSet.getValue(0x0008, 0x1199));
			ICollectionIterator<IItem> objSQItemIterator = objSQReferencedSOPSequenceItem.iterator();
			while(objSQItemIterator.hasNext())
			{
				IItem objItem = objSQItemIterator.next();
				ICollectionIterator<IDataElement> objDataElementIterator = objItem.iterator();
				OnlineElectronicStorageSecureUseProfile objSecureUseProfile = OnlineElectronicStorageSecureUseProfile.getOnlineElectronicStorageSecureUseProfile();
				while(objDataElementIterator.hasNext())
				{
					IDataElement objDataElement = objDataElementIterator.next();
					String strSopInstanceUID = objDataElement.getDicomValue().toString();
					// Confirming whether Storage Commitment Expected
					if(objSecureUseProfile.isStorageCommitmentConfirmationExpected(strSopInstanceUID))
					{
						String strFilePath = objSopInstanceFilePathCollection.get(strSopInstanceUID);
						String strSopClassID = objSopInstanceSopClassCollection.get(strSopInstanceUID);
						store(strFilePath,strSopClassID,strStoragePath);
					}
					else
						System.out.println("Confirmation not expected from Storage Security Profile for Instance ID = "+strSopInstanceUID);
				}
			}	
		}
		catch(SerializeException se)
		{
			if(DicomConfig.createInstance().isLoggingOn())
			{
				DicomLogger.getLogger().log(se.getMessage());
			}
			throw new SinkException(ResourceBundleWrapper.getValue("exceptions", "STORAGECOMMITMENT.StorageException", new Locale(DicomConfig.createInstance().getLocale())),se);
		}
		catch(IOException ie)
		{
			if(DicomConfig.createInstance().isLoggingOn())
			{
				DicomLogger.getLogger().log(ie.getMessage());
			}
			throw new SinkException(ResourceBundleWrapper.getValue("exceptions", "STORAGECOMMITMENT.StorageException", new Locale(DicomConfig.createInstance().getLocale())),ie);
		}
		return EnumImplOpsStatus.SUCCESS.getValue();
	}

	//The implementation of this method still needs to be provided.
	public short store(IQueryModel objQueryModel,String strStoragePath) throws SinkException
	{
		return EnumImplOpsStatus.FAILURE.getValue();
	}


}
