package jp.co.y_net.amm.common;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.mail.Address;
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.MimeMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class AppSendMail {
    private static Logger loggerSlfMail = LoggerFactory.getLogger("AmmMail");
    public static void loggingTest(String msg) {
        loggerSlfMail.info(msg);
    }
    
    public static class MailSetting{
        private String mailTo;
        private String title;
        private String body;
        public void setMailTo(String mailTo) {
            this.mailTo = mailTo;
        }
        public void setTemplate(String text) {
            String tmp = text;
            List<String> lines = Arrays.asList(tmp.split("\n"));
            for (String line: lines) {
                if(title == null) {
                    title = line; // １行目はタイトル
                } else {
                    if(body == null) body = "";
                    body += line + "\n";
                }
            }
        }
        public void replace(String key, String value) {
            body = body.replace("@"+ key +"@", value);
        }
        
        @Override
        public String toString() {
            return "MailSetting [title=" + title + ", body=" + body + "]";
        }
    }
    
    public static boolean send(MailSetting mainSetting) {
        
        Properties objPrp = new Properties();
        objPrp.put("mail.smtp.host", ResourceReader.getStringQuick("Smtp"));
        objPrp.put("mail.host", ResourceReader.getStringQuick("Smtp"));
        objPrp.put("mail.from", ResourceReader.getStringQuick("MailFrom"));
        
        /* メールセッションを確立 */
        Session mailSes = Session.getDefaultInstance(objPrp,null);
        
        /* 送信メッセージを生成 */
        MimeMessage objMsg = new MimeMessage(mailSes);
        
        try {
            /* 設定：送信先 */
            List<Address> lstAddress = new ArrayList<Address>();
            Address to1 = new InternetAddress(mainSetting.mailTo);
            lstAddress.add(to1);
            Address[] to = (Address[]) lstAddress.toArray(new Address[0]);
            objMsg.setRecipients(Message.RecipientType.TO, to);
            
            /* 設定：Fromヘッダ */
            InternetAddress objFrm = new InternetAddress(ResourceReader.getStringQuick("MailFrom"));
            objMsg.setFrom(objFrm);

            /* 設定：件名 */
            objMsg.setSubject(mainSetting.title, "ISO-2022-JP");
            
            /* 設定：本文 */
            String honbun = AppStringUtils.utf8ToSjis(mainSetting.body);
            objMsg.setText(new String(honbun.getBytes("ISO-2022-JP")), "ISO-2022-JP");
            objMsg.setSentDate(new Date());
            
            /* 送信メールのロギング */
            
            loggerSlfMail.info("-----------------------------------------------------------");
            loggerSlfMail.info("Recipients:" + mainSetting.mailTo);
            loggerSlfMail.info("Subject:" + mainSetting.title);
            loggerSlfMail.info("Text:" + mainSetting.body);
            
            
            /* メール送信実行 */
            Transport.send(objMsg);
            
            loggerSlfMail.info("Result:Success");
            return true;
            
        } catch (MessagingException e) {
            loggerSlfMail.info("Result:Failure!!(see application log...)");
            AppLogger.error(e);
            return false;
        } catch (UnsupportedEncodingException e) {
            loggerSlfMail.info("Result:Failure!!(see application log...)");
            AppLogger.error(e);
            return false;
        }
    }

    /*
     * メールサーバー構築
     * http://itpro.nikkeibp.co.jp/article/COLUMN/20060427/236452/
     * https://technet.microsoft.com/ja-jp/library/cc772058%28v=ws.10%29.aspx
     *  サーバーマネージャー＞機能ビュー
     */
    
    public static void main(String[] args) {
        // TODO インフラに ZASEKI サーバー 25ポート を開けてもらってテスト。
        
        //sendMail();
        
        /*
         * 新着申請内容受信メール
         */
        MailSetting setting = new MailSetting();
        setting.setTemplate(ResourceReader.getText("message/mail.orgentry"));
        setting.mailTo = ResourceReader.getStringQuick("mailto.olgentry");
        setting.replace("申請画面URL", "http://localhost:8080/AMM/orgentrydetail?orgid=" + 3);
        send(setting);
        
        System.out.println(setting.toString());
    }
    
}

