package nlib.util;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import egovframework.com.cmm.EgovWebUtil;
import egovframework.com.utl.fcc.service.EgovStringUtil;
import nlib.bbs.service.impl.QnaServiceImpl;
import nlib.mail.EmailSender;
import nlib.mail.service.EmailVO;

/**
 * <pre>
 * @Class Name : EmailUtil.java
 * 
 * @Description : 이메일 관련 유틸리티 기능 모음 클래스 
 * 
 * 
 * @프로젝트명: 지방문화원 통합자료관리시스템 구축사업 (2021)
 *
 * </pre>
 *
 * @ ------------    --------    ---------------------------
 * @ 수정일                     수정자             수정내용
 * @ ------------    --------    ---------------------------
 * @ 2021. 9. 16.    JSYOo       최초 생성
 *
 * 
 * @author 이씨플라자 * DIGITALSHIP JSYOO
 * @since 2021. 9. 16.
 * @version 1.0
 *
 */
@Component("emailUtil")
public class EmailUtil{

	static Logger log = LoggerFactory.getLogger(EmailUtil.class);
	
	@Autowired
    private EmailSender emailSender;
	
	
	/** 메일발송
	 * @param reciverEmail
	 * @param subject
	 * @param replaceContents
	 * @param templateFilePath
	 * @throws Exception
	 */
	public String sendEmail(String reciverEmail, String subject, Map<String, Object> replaceContents, String templateFilePath) throws Exception {
		EmailVO email = new EmailVO();
		String error="";
    	Path path = Paths.get(templateFilePath);
    	Charset cs = StandardCharsets.UTF_8;
    	List<String> list = new ArrayList<String>();
    	String contents = "";
    	try {
    		list = Files.readAllLines(path,cs);
    	}catch(IOException e) {
    		error=getPrintStackTrace(e);
    	}
    	
    	if(!error.equals(""))
    	{
    		log.error(error);
    		return "templateFail";
    	}
    	for(String readLine : list) {
    		contents+=readLine;
    	} 
    	Set set = replaceContents.keySet();

    	Iterator iterator = set.iterator();
    	
    	while(iterator.hasNext()){
			  String key = (String)iterator.next();
			  contents=contents.replace(key,(CharSequence) replaceContents.get(key));
		}
    	email.setReciver(reciverEmail);
        
        email.setSubject(subject);
        email.setContent(contents);
        emailSender.SendEmail(email);
        return "success";
	}
	public static String getPrintStackTrace(Exception e) {
        
        StringWriter errors = new StringWriter();
        e.printStackTrace(new PrintWriter(errors));
         
        return errors.toString();
         
    }
}
