package cmm.util;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import egovframework.com.cmm.service.EgovProperties;

public class MailUtil {

	private static final Log log = LogFactory.getLog(MailUtil.class);
	
	public static void sendMail(String toAddr, String toName, String msgSubj, String msgText) {
    	try{
    		Properties mailProps = new Properties();

    		mailProps.put("mail.smtp.starttls.enable", "true");
    		mailProps.put("mail.smtp.host", EgovProperties.getProperty("Globals.mail.smtp.host"));
    		mailProps.put("mail.smtp.auth", "true");
    		mailProps.put("mail.smtp.port", EgovProperties.getProperty("Globals.mail.smtp.port"));
    		
    		
    		Authenticator auth = new MyAuthentication();
            //session 생성 및  MimeMessage생성
    		Session _session = Session.getDefaultInstance(mailProps, auth);
    		
    		String fromAddr = EgovProperties.getProperty("Globals.mail.smtp.user");
    		String fromName = EgovProperties.getProperty("Globals.mail.smtp.username");
    		
    		MimeMessage msg = new MimeMessage(_session);
    		msg.setFrom(new InternetAddress(fromAddr, fromName));
    		InternetAddress[] address = {new InternetAddress(fromAddr, toName)};
    		msg.setRecipients(Message.RecipientType.TO, address);
    		
    		/*참조인원*/
    		InternetAddress[] addresscc = {new InternetAddress(EgovProperties.getProperty("Globals.mail.cc.user01")), 
    										new InternetAddress(EgovProperties.getProperty("Globals.mail.cc.user02")),
								    		new InternetAddress(EgovProperties.getProperty("Globals.mail.cc.user03")),
								    		new InternetAddress(EgovProperties.getProperty("Globals.mail.cc.user04"))
    		};
    		msg.setRecipients(Message.RecipientType.CC, addresscc);
    		
    		msgSubj = "Q&A가 등록되었습니다.";
    		msg.setSubject(msgSubj);
    		msg.setSentDate(new Date());
    		msgText = "Q&A가 등록되었습니다. 관리자사이트에서 Q&A를 확인하시기 바랍니다.";
    		// 이메일 제목
            msg.setSubject(msgSubj, "UTF-8");
            // 이메일 내용
            msg.setText(msgText, "UTF-8");
            // 이메일 헤더
            msg.setHeader("content-Type", "text/html");
            //메일보내기
    		Transport.send(msg);    
    		
    	}catch(MessagingException e){
            log.error("Error in sendMail()", e);
    	}catch (UnsupportedEncodingException e) {
    		log.error("Error in sendMail()", e);	
		}
	}
	public static void sendMailHtml(HttpServletRequest request, String toAddr, String toName, String msgSubj, String msgText) {
    	try{
    		String serverPath = request.getContextPath(); // 서버패스
    		String htmlFilePath = EgovProperties.getProperty("Globals.mail.html.path");
    		String htmlFileName = EgovProperties.getProperty("Globals.mail.html.file");
    		
    		Properties mailProps = new Properties();
    		

    		mailProps.put("mail.smtp.host", EgovProperties.getProperty("Globals.mail.smtp.host"));
    		Session _session = Session.getInstance(mailProps, null);

    		String fromAddr = EgovProperties.getProperty("Globals.mail.smtp.user");
    		String fromName = EgovProperties.getProperty("Globals.mail.smtp.username");
    		
    		MimeMessage msg = new MimeMessage(_session);
    		msg.setFrom(new InternetAddress(fromAddr, fromName));
    		InternetAddress[] address = {
    			new InternetAddress(toAddr, toName)
    		};

    		msg.setRecipients(Message.RecipientType.TO, address);

    		msg.setSubject(msgSubj);

    		msg.setSentDate(new Date());

    		MimeMultipart cont = new MimeMultipart();
    		MimeBodyPart txt = new MimeBodyPart();

    		txt.setText(msgText, "EUC-KR"); //"ks_c_5601-1987"
    		txt.setHeader("Content-Type", "text/html; charset=\"EUC-KR\""); //charset=\"ks_c_5601-1987\""
    		txt.setHeader("Content-Transfer-Encoding", "base64");

    		/// html 값을 리플레이스.
    		String html = getMailBodyHtml(htmlFilePath+htmlFileName);
    		html.replace("$title$", msgSubj);
    		
    		cont.addBodyPart(txt);
    		msg.setText(html);
    		msg.setContent(cont);
    		msg.saveChanges();

    		Transport.send(msg);    
    		
    	}catch(MessagingException e){
            log.error("Error in sendMail()", e);
    	}catch (UnsupportedEncodingException e) {
    		log.error("Error in sendMail()", e);	
		}
	}
	public static String getMailBodyHtml(String pathFile){
		String html = "";
		if(StringUtils.isBlank(pathFile) ){
			return html;
		}else{
			BufferedReader br = null ;
			try {
				br = new BufferedReader(new FileReader(pathFile));
		        while(true) {
		        	String temp = br.readLine();
		            if (temp==null) break;
		            html += temp;
		        }
		        br.close();
			} catch (Exception e) {
			}finally {
				try {
					br.close();
				} catch (IOException e) {
				}
			}
		}
		return html;
	}
	
}
