/*******************************************************************************
 *  Copyright 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.services.generalpurposemimeinterchangeprofile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Locale;
import java.util.Properties;
import java.util.Random;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import cdac.medinfo.sdk.dcm30_04.services.generalpurposecompressioninterchangeprofiles.MediaStorageCompress_FSC;
import cdac.medinfo.sdk.dcm30_04.utils.DicomConfig;
import cdac.medinfo.sdk.dcm30_04.utils.DicomLogger;
import cdac.medinfo.sdk.dcm30_04.utils.ResourceBundleWrapper;
import cdac.medinfo.sdk.dcm30_04.utils.StandardMethods;

/**
 * This class is implemented to use DIMSE_M-Services.
 * The MediaStorage_Mail_FSC supports the Media Storage Operations M-Write, M-Inquire File and M-Inquire File-Set.
 * It checks available free space on disk and creates DICOM DIR File Set on Disk.
 * It sends DICOM DIR File-Set via Email.
 * */
public class MediaStorageMail_FSC
{
	/**
	 * This function create DicomDir File-Set by calling process() of MediaStorage_FSC class.
	 * It compresses DICOM DIR File-Set call compressDicomDir function.
	 * It sends Dicom Dir File Set via mail.
	 * @param strFileName,strStoragePath,username,password,Toemail
	 * @throws MessagingException 
	 * @throws AddressException 
	 * @throws IOException
	 * */
	public void process(String strFileName, String strStoragePath,String username ,String password, String toEmail) throws IOException, AddressException, MessagingException
	{
		String strStoragePath2;
		Random ran = new Random();

		if(strStoragePath == null||strStoragePath == "" ||strStoragePath == "null"||strStoragePath.isEmpty())
		{
			strStoragePath2 = StandardMethods.getTempDirectoryStorage() + "CDAC-SDK/DCM-J/Storage"+"/DICOM"+ran.nextInt(1000);

		}
		else
		{
			strStoragePath2 = strStoragePath+"/DICOM"+ran.nextInt(1000); 
		}
		if(username == null||username == "" ||username == "null"||username.isEmpty()||password == null||password == "" ||password == "null"||password.isEmpty()||toEmail == null||toEmail == "" ||toEmail == "null"||toEmail.isEmpty())
		{
			DicomLogger.getLogger().log(ResourceBundleWrapper.getValue("warning", "PrimaryAttributeMissing", new Locale(DicomConfig.createInstance().getLocale())));
		}
		else
		{
			MediaStorageCompress_FSC objMediaStorage_Compress_FSC = new MediaStorageCompress_FSC();
			String strStoragePath3 =objMediaStorage_Compress_FSC.process(strFileName, strStoragePath2);
			String zipFileName = strStoragePath3.concat(".zip");
			sendEmail(zipFileName,username ,password, toEmail);
		}
	}
	/**
	 * This Part of code mail DICOM-Dir File Set .
	 * @throws IOException 
	 */
	public static void sendEmail(String filename,final String username ,final String password, String Toemail) throws AddressException, javax.mail.MessagingException, MessagingException, IOException
	{
		Properties props = new Properties();
		InputStream input = MediaStorageMail_FSC.class.getResourceAsStream("email_configuration.properties");
		props.load(input);
		String auth = props.getProperty("smtpauth");
		props.put("mail.smtp.auth", auth);
		String hostnew =  "smtp."+props.getProperty("host")+".in";
		props.put("mail.smtp.host",hostnew);
		String port = props.getProperty("smtpport");
		props.put("mail.smtp.port", port);
		Session session1 = Session.getInstance(props, new javax.mail.Authenticator() 
		{protected PasswordAuthentication getPasswordAuthentication() {return new PasswordAuthentication(username, password);} });
		MimeMessage message = new MimeMessage(session1);  
		message.setFrom(new InternetAddress(username));  
		message.addRecipient(Message.RecipientType.TO,new InternetAddress(Toemail));  
		message.setSubject("DicomDir File Set");
		BodyPart messageBodyPart = new MimeBodyPart();
		// Fill the message
		messageBodyPart.setText("Sending Dicom Dir File Set");
		// Create a multipart message
		Multipart multipart = new MimeMultipart();
		// Set text message part
		multipart.addBodyPart(messageBodyPart);
		// Part two is attachment
		messageBodyPart = new MimeBodyPart();
		DataSource source = new FileDataSource(filename);
		messageBodyPart.setDataHandler(new DataHandler(source));
		File fName = new File(filename);
		String FNameAttachment =fName.getName();
		messageBodyPart.setFileName(FNameAttachment);
		multipart.addBodyPart(messageBodyPart);
		// Send the complete message parts
		message.setContent(multipart );
		// Send message
		Transport.send(message);
		DicomLogger.getLogger().log(ResourceBundleWrapper.getValue("status", "MailSend", new Locale(DicomConfig.createInstance().getLocale())));
	}
}
