package jp.sourceforge.mailagent;

import java.io.File;
import java.io.StringWriter;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import org.apache.log4j.Logger;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;

/**
 * MailAgent幚憰
 */
class MailAgentImpl  implements MailAgent{
   private MailConfig config;      // 儊乕儖憲怣愝掕
   private String mailbody;             // 儊乕儖俛倧倓倷
   private MailSource mailSource;       // 儊乕儖憲怣僜乕僗
   private Template template;   // Velocity 儊乕儖僥儞僾儗乕僩
   private Logger logger;
   protected MailAgentImpl(){
      this.mailSource = new MailSource();
      this.logger = Logger.getLogger("mailagent");
   }

   /* 儊乕儖憲怣乮僗儗僢僪幚峴乯.
    * @see jp.sourceforge.mailagent.MailAgent#post()
    */
   public void post(){
      SendmailThread sm = new SendmailThread(this.mailSource);
      sm.setSMTP(this.config.getSmtphost()
                 ,this.config.isSmtpauth()
                 ,this.config.getSmtpuser()
                 ,this.config.getSmtppasswd()
                 ,this.config.getTimeout());
      sm.setEncode(this.config.getEncode());
      Thread th = new Thread(sm);
      th.start();
   }
   /* 儊乕儖憲怣乮寢壥嶲徠乯.
    * @see jp.sourceforge.mailagent.MailAgent#send()
    */
   public ResultMail send(){
      SendmailThread sm = new SendmailThread(this.mailSource);
      sm.setSMTP(this.config.getSmtphost()
            ,this.config.isSmtpauth()
            ,this.config.getSmtpuser()
            ,this.config.getSmtppasswd()
            ,this.config.getTimeout());
      sm.setEncode(this.config.getEncode());
      return sm.send();
   }
   //===========================================================================================
   /* TO丗愝掕.
    * @see jp.sourceforge.mailagent.MailAgent#setTO(java.lang.String[])
    */
   public void setTO(String[] toary){
      for(int i=0;i < toary.length;i++){
         this.mailSource.setTo(toary[i],null);
      }
   }
   /* TO丗愝掕乮僄僀儕傾僗巜掕乯
    * @see jp.sourceforge.mailagent.MailAgent#setTO(java.util.Map)
    */
   public void setTO(Map<String,String> tomap){
      for(Iterator<String> it=tomap.keySet().iterator();it.hasNext();){
         String key = it.next();
         this.mailSource.setTo(key,tomap.get(key));
      }
   }
   //===========================================================================================
   /* CC丗愝掕
    * @see jp.sourceforge.mailagent.MailAgent#setCC(java.lang.String[])
    */
   public void setCC(String[] ccary){
      for(int i=0;i < ccary.length;i++){
         this.mailSource.setCC(ccary[i],null);
      }
   }
   /* CC丗愝掕乮僄僀儕傾僗巜掕乯
    * @see jp.sourceforge.mailagent.MailAgent#setCC(java.util.Map)
    */
   public void setCC(Map<String,String> ccmap){
      for(Iterator<String> it=ccmap.keySet().iterator();it.hasNext();){
         String key = it.next();
         this.mailSource.setCC(key,ccmap.get(key));
      }
   }
   //===========================================================================================
   /* BCC丗愝掕
    * @see jp.sourceforge.mailagent.MailAgent#setBCC(java.lang.String[])
    */
   public void setBCC(String[] bccary){
      for(int i=0;i < bccary.length;i++){
         this.mailSource.setBCC(bccary[i],null);
      }
   }
   /* BCC丗愝掕乮僄僀儕傾僗巜掕乯
    * @see jp.sourceforge.mailagent.MailAgent#setBCC(java.util.Map)
    */
   public void setBCC(Map<String,String> bccmap){
      for(Iterator<String> it=bccmap.keySet().iterator();it.hasNext();){
         String key = it.next();
         this.mailSource.setBCC(key,bccmap.get(key));
      }
   }
   //===========================================================================================
   /* 憲怣幰傾僪儗僗愝掕
    * @see jp.sourceforge.mailagent.MailAgent#setFROM(java.lang.String)
    */
   public void setFROM(String from){
      this.mailSource.setFrom(from,null);
   }

   /* 憲怣幰傾僪儗僗仌僄僀儕傾僗愝掕
    * @see jp.sourceforge.mailagent.MailAgent#setFROM(java.lang.String, java.lang.String)
    */
   public void setFROM(String from,String alias){
      this.mailSource.setFrom(from,alias);
   }

   /* 曉怣愭傾僪儗僗愝掕
    * @see jp.sourceforge.mailagent.MailAgent#setReplyTo(java.lang.String)
    */
   public void setReplyTo(String replyTo){
      this.mailSource.setReplyto(replyTo);
   }
   //===========================================================================================
   /* 儊乕儖審柤僙僢僩
    * @see jp.sourceforge.mailagent.MailAgent#setSubject(java.lang.String)
    */
   public void setSubject(String subject){
      this.mailSource.setSubject(subject);
   }
   //===========================================================================================
   /* 儊乕儖杮暥僙僢僩乮僥儞僾儗乕僩側偟乯
    * @see jp.sourceforge.mailagent.MailAgent#setBody(java.lang.String)
    */
   public void setBody(String body){
      if (body==null){ throw new IllegalArgumentException("仧 mail body is null"); }
      if (body.length()==0){ throw new IllegalArgumentException("仧 mail body length is 0"); }
      this.mailSource.setMessage(Encode.convProphibitCode(Encode.convCp932toJIS(body)));
   }
   /* 儊乕儖杮暥僙僢僩乮僥儞僾儗乕僩巜掕乯
    * @see jp.sourceforge.mailagent.MailAgent#setBody(java.util.Map)
    */
   public void setBody(Map<String,Object> map){
      if (this.template==null){
         throw new NullPointerException("仧 template not Config");
      }
      this.mailbody = "";
      VelocityContext context = new VelocityContext();  // VelocityContext
      // 抲姺偊Map傪VelocityContext偵僙僢僩
      if (map != null){
         Set<String> keySet = map.keySet();
         for (Iterator<String> it=keySet.iterator();it.hasNext();){
            String key = it.next();
            context.put(key,map.get(key));
         }
      }
      // 儊乕儖僥儞僾儗乕僩偲儅乕僕
      try{
      StringWriter sw = new StringWriter();
      this.template.merge(context,sw);
      sw.close();
      this.mailbody = Encode.convProphibitCode(Encode.convCp932toJIS(sw.toString()));
      }catch(ResourceNotFoundException e){
         throw e;
      }catch(ParseErrorException e){
         throw e;
      }catch(Exception e){
         throw new RuntimeException("仧 Exception :"+e.getMessage(),e);
      }finally{
         this.mailSource.setMessage(this.mailbody);
      }
   }
   //===========================================================================================
   /* 揧晅僼傽僀儖僙僢僩
    * @see jp.sourceforge.mailagent.MailAgent#setTempFiles(java.io.File[])
    */
   public void setTempFiles(File...temps){
      this.mailSource.setTemp(temps);
   }
   //===========================================================================================
   /* 儊乕儖憲怣偺堊偺埗愭丄憲怣幰丄儊僢僙乕僕丄慡偰傪僋儕傾偡傞丅
    * @see jp.sourceforge.mailagent.MailAgent#clearAll()
    */
   public void clearAll(){
      this.mailSource.clearAll();
   }
   /* 僙僢僩偝傟偨埗愭丄TO,CC,BCC傪僋儕傾偡傞丅
    * @see jp.sourceforge.mailagent.MailAgent#clearTo()
    */
   public void clearTo(){
      this.mailSource.clearTo();
   }
   //===========================================================================================
   /* 僥儞僾儗乕僩偱嶌惉偝傟偨儊乕儖杮暥暥帤楍傪嶲徠
    * @see jp.sourceforge.mailagent.MailAgent#getMessage()
    */
   public String getMessage(){
      return this.mailSource.getMessage();
   }
   //===========================================================================================
   /* 儊乕儖愝掕.
    * @see jp.sourceforge.mailagent.MailAgent#setMailConfig(jp.sourceforge.mailagent.MailConfig)
    */
   public void setMailConfig(MailConfig config){
      this.config = config;
      StringBuffer sb = new StringBuffer();
      sb.append("仭仭仭仭仭仭仭仭仭仭仭仭仭仭仭仭仭仭仭仭仭仭仭仭仭仭仭仭仭仭仭"+"\n");
      sb.append("\t\t"+"仭 --------------- MailAgent init Config ---------------\n");
      sb.append("\t\t"+"仭 SMTP_HOST    = "+this.config.getSmtphost()+"\n");
      sb.append("\t\t"+"仭 TIMEOUT      = "+Integer.toString(this.config.getTimeout())+" sec"+"\n");
      sb.append("\t\t"+"仭 SMTP_AUTH    = "+this.config.isSmtpauth()+"\n");
      sb.append("\t\t"+"仭 SMTP_USER    = "+this.config.getSmtpuser()+"\n");
      sb.append("\t\t"+"仭 SMTP_PASSWD  = "+this.config.getSmtppasswd()+"\n");
      sb.append("\t\t"+"仭 MAIL_ENCODE  = "+this.config.getEncode()+"\n");
      this.logger.debug(sb.toString());
   }
   /* 僥儞僾儗乕僩愝掕
    * @see jp.sourceforge.mailagent.MailAgent#setTemplate(org.apache.velocity.Template)
    */
   public void setTemplate(Template template){
      this.template = template;
   }

}
