package jp.ac.do_johodai.j314.sw.je;

import java.net.*;
import java.io.*;
import com.hp.hpl.jena.graph.*;
import com.hp.hpl.jena.reasoner.rulesys.builtins.BaseBuiltin;
import com.hp.hpl.jena.reasoner.rulesys.RuleContext;
import com.hp.hpl.jena.reasoner.rulesys.BindingEnvironment;

/**
 * SMTPでメールを出すためのビルトイン。ビルトインの名前は'smail'。
 * 第1引数はSMTPサーバのホスト名
 * 第2引数は差出人のメールアドレス
 * 第3引数は受取人のメールアドレス
 * 第4引数は件名(Subject)
 * 第5引数は本文
 */
public class SMailBuiltin extends BaseBuiltin {
    public String getName() {
        return "smail";
    }

    public int getArgLength() {
        return 5;
    }

    public boolean bodyCall(Node[] args, int length, RuleContext context) {
        return smail(args,length,context);
    }

    public void headAction(Node[] args, int length, RuleContext context) {
        smail(args,length,context);
    }

    boolean smail(Node[] args, int length, RuleContext context) {
        try {
            if (length != 5)
                return false;
            String host    = ((Node_Literal)args[0]).getLiteralLexicalForm();
            String from    = ((Node_Literal)args[1]).getLiteralLexicalForm();
            String to      = ((Node_Literal)args[2]).getLiteralLexicalForm();
            String subject = ((Node_Literal)args[3]).getLiteralLexicalForm();
            String body    = ((Node_Literal)args[4]).getLiteralLexicalForm();

            Socket socket = new Socket(host, 25);
            OutputStream os = socket.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(os,"ISO-2022-JP");
            PrintWriter out = new PrintWriter(osw, true);
            InputStreamReader isr = new InputStreamReader(socket.getInputStream());
            BufferedReader in = new BufferedReader(isr);
            out.println("HELO");
            in.readLine();
            out.println("MAIL FROM: "+from);
            in.readLine();
            out.println("RCPT TO: "+to);
            in.readLine();
            out.println("DATA");
            in.readLine();
            out.println("From: "+from);
            out.println("To: "+to);
            out.println("Subject: "+subject);
            out.println("");
            out.println(body);
            out.println(".");
            in.readLine();
            out.println("quit");
            in.readLine();

            out.close();
            in.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
