package jforex;

import java.util.Date;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.Message.RecipientType;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import com.dukascopy.api.*;

/**
* @author Denis Larka 13 Jun 2008
*/

@Library("C:\\temp\\mail-1.4.jar")
public class TestMail implements IStrategy {

    @Configurable("SMTP Server")
    public String smtpServer = "localhost";


    private IContext context;

    private IConsole console;

    private IEngine engine;

    private IChart chart;

    public void onAccount(IAccount account) throws JFException {
    }

    public void onMessage(IMessage message) throws JFException {
    }

    public void onStart(IContext context) throws JFException {
        this.context = context;
        this.engine = context.getEngine();
        this.console = context.getConsole();
    }

    public void onStop() throws JFException {
    }

    public void onTick(Instrument instrument, ITick tick) throws JFException {
        try {
            print(smtpServer);
            sendMail("somemail@address.com", "somemail@address.com", "Hello", "SWFX");
        } finally {
            context.stop();
        }
    }

    public void onBar(Instrument instrument, Period period, IBar askBar, IBar bidBar) throws JFException {
    }

    private void print(String str) {
        console.getOut().println(str);
    }

    public boolean sendMail(String from, String to, String subj, String text) throws JFException {
        try {
            Properties props = new Properties();//System.getProperties();
            // Attaching to default Session, or we could start a new one
            props.setProperty("mail.smtp.host", smtpServer);
            Session session = null;
            session = Session.getInstance(props);
            // Create a new message
            Message msg = new MimeMessage(session);
            // Set the FROM field
            msg.setFrom(new InternetAddress(from));
            // Set the TO fields
            msg.setRecipient(RecipientType.TO, new InternetAddress(to));
            // Set the subject and body text
            msg.setSubject(subj);
            msg.setText(text);
            // Set some other header information
            msg.setHeader("SWFX-Mailer", "SWFX");
            msg.setSentDate(new Date());
            // Send the message
            Transport.send(msg);
            return true;
        } catch (Exception e) {
            throw new JFException(e);
        }
    }

}