/*******************************************************************************
 *  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.tools.imageconverter;

import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;

import org.w3c.dom.Text;

import cdac.medinfo.sdk.dcm30_04.commoninterface.IDataSet;
import cdac.medinfo.sdk.dcm30_04.dicomparserserializers.DicomParser;
import cdac.medinfo.sdk.dcm30_04.enums.EnumLoggingLevel;
import cdac.medinfo.sdk.dcm30_04.utils.DicomConfig;
import cdac.medinfo.sdk.dcm30_04.utils.StandardMethods;

public class ImageConverter 
{
	private Text txtContentNode = null;
	static int lengthOfOption = 18;
	static int lengthOfDetails = 79 - lengthOfOption;
	/**
	 * @param args
	 */
	public static void main(String[] args)
	{
		EnumLoggingLevel enumlogginglevel = EnumLoggingLevel.SEVERE;
		String strLogDir = null;
		
		ImageConverter objImageConverter = new ImageConverter();
		String strDCMFile = null;
		String strDestFolder = null;

		String strIniFile = null;
		String strKey = null;

//		 args = new String[4];
//		 args[0]="-f";
//		args[1]="F:\\Zircon-Related\\TestDicomFiles\\JPEG Baseline process1\\0003.DCM";
//		args[2]="-s";
//		args[3]="D:\\BMP";
		if(args == null || args.length == 0)
		{
			objImageConverter.displayHelp();
			System.exit(0);
		}

		for(int i = 0; i < args.length; i++)
		{
			if(args[i].equalsIgnoreCase("-l") && args.length > i + 1)
			{
				String strLoggingMode= args[i + 1];
				if(strLoggingMode.equalsIgnoreCase("i"))
				{
					enumlogginglevel = EnumLoggingLevel.INFO;
				} else
					if(strLoggingMode.equalsIgnoreCase("s"))
					{
						enumlogginglevel = EnumLoggingLevel.SEVERE;
					} else
					{
						System.out.println("Not a Valid Command. The value of logging mode can be INFO(I) or SEVER(S)");
						objImageConverter.displayHelp();
						System.exit(0);
					}
				i++;
				continue;
			}
			if(args[i].equalsIgnoreCase("-d") && args.length > i + 1)
			{
				strLogDir = args[i + 1];
				i++;
				continue;
			}
			if(args[i].equalsIgnoreCase("-v") && args.length > i + 1)
			{
				
				i++;
				continue;
			}
			if(args[i].equalsIgnoreCase("-f") && args.length > i + 1)
			{
				strDCMFile = args[i + 1];
				i++;
				continue;
			}	
			if(args[i].equalsIgnoreCase("-s") && args.length > i + 1)
			{
				strDestFolder = args[i + 1];
				i++;
				continue;
			}
			if (args[i].trim().equalsIgnoreCase("-z") && args.length > i + 1)
			{
				String temp = args[i + 1].trim();
				String[] valueArray = temp.split("#");
				if (valueArray.length != 2)
				{
					System.out.println("Not a valid command");
					objImageConverter.displayHelp();
					System.exit(0);
				}
				strIniFile = valueArray[0];
				strKey = valueArray[1];
				i++;
				continue;
			}
		}

		try
		{
			DicomConfig dicomconfig = DicomConfig.createInstance();
			dicomconfig.enableLogging(enumlogginglevel, strLogDir);
			
			
			String struuid = StandardMethods.generateUUID();

			if(strDCMFile != null)
			{

				DicomParser objDicomParser = new DicomParser();
				IDataSet objSRCDataSet = objDicomParser.parseAsPart10File(strDCMFile,true);
				
				if(strDestFolder == null)
					strDestFolder = System.getProperty("java.io.tmpdir")+"/CDAC-SDK/DCM-J/DicomDump/";

					DICOMImageInfoReader objDicomImageInfoReader = new DICOMImageInfoReader();
					objDicomImageInfoReader.readDICOMImageInfo(objSRCDataSet);
					
					int iNumberOfFrames = objDicomImageInfoReader.getNumberOfFrames();
					
					if(iNumberOfFrames >10)
						iNumberOfFrames =10;
					
					
					for(int i =0; i < iNumberOfFrames; i++)
					{
						
						DICOMImageConvertor objDicomImageConvertor = new DICOMImageConvertor();
						BufferedImage objBufferedImage = objDicomImageConvertor.processImage(objDicomImageInfoReader, i, objDicomImageInfoReader.getFrame(i));
						ImageIO.write(objBufferedImage, "BMP", new File(strDestFolder + "/" + struuid + "_" + i+1 + ".bmp"));
					}					
					
					
			}
			else
			{			
				System.out.println("Not a valid command,	 Source DICOM file for Image conversion is not specified.");
				objImageConverter.displayHelp();
				System.exit(0);
			}
		}
		catch(Exception exception)
		{
			System.out.println("Operation failed :" + exception.getMessage());
		}
	}



	private void displayHelp()
	{
		System.out.println("\nImageConverter :: Converts the DICOM file to BMP document.");

		System.out.println("\nImageConverter [-d LogDir] [-l LogMode] " +
		"-f DCMfile \n [-s DestinationFolder] \n");

		printToConsole("-d", "Log directory");
		printToConsole("", "User's temp directory is taken as default.");
		
	
		printToConsole("-l", "Log mode");
		String as1[] = {
				"I INFO", "S SEVER"
		};
		printToConsole("LogMode", as1);
		printToConsole("", "Default Logging Mode is INFO");
		printToConsole("-f", "Source DICOM file for BMP conversion.");
		printToConsole("-s", "Destination folder path to store converted BMP file.");
		printToConsole("", "User's temp directory is taken as default.");

		System.out.println("\nExample :");

		System.out.println("\n1. ImageConverter -f image.dcm -s C:/BMPContent " +
		"\nConverts the image.dcm to its BMP representation and stores same to folder \nC:/BMPContent.");

	}

	/**
	 * Display Help of command on console in proper manner.
	 * @param strOption Option for command.
	 * @param strDetails Description of option.
	 */
	public static void printToConsole(String strOption, String strDetails)
	{
		String strBuffer = "";
		if (strOption != null)
			strBuffer = strBuffer + strOption ;
		while (lengthOfOption > strBuffer.length())
		{
			strBuffer = strBuffer + " ";
		}
		if (strDetails != null)
		{
			if (strDetails.length() < lengthOfDetails || strDetails.length() == lengthOfDetails)
			{
				strBuffer = strBuffer + strDetails;
				strDetails = null;
			}
			else
			{
				strBuffer = strBuffer + strDetails.substring(0, lengthOfDetails);
				strDetails = strDetails.substring(lengthOfDetails, (strDetails.length() ));
			}
		}

		System.out.println(strBuffer);
		if (strDetails == null)
			return;
		else
			printToConsole(null, strDetails);
	}

	/**
	 * Display Help of command on console in proper manner.
	 * @param strAttribute Attribute for option.
	 * @param strDesc Description of attributes.
	 */
	public static void printToConsole(String strAttribute, String[] strDesc)
	{
		if (strDesc.length > 1)
			printToConsole(strAttribute, strDesc[0]);
		for(int i = 1;i<strDesc.length;i++)
			printToConsole(null, strDesc[i]);
	}

}
