/*
 * Copyright 2016 Objectos, Fábrica de Software LTDA.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package br.com.objectos.way.mail;

import br.com.objectos.way.testable.Equality;
import br.com.objectos.way.testable.Testable;
import br.com.objectos.way.testable.Tester;
import br.com.objectos.way.core.Throwables;
import java.io.UnsupportedEncodingException;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.MimeMessage;

/**
 * @author marcio.endo@objectos.com.br (Marcio Endo)
 */
public class Mail implements Testable {

  private static final Tester<Mail> TESTER = Tester.of(Mail.class)
      .add("builder", o -> o.builder)
      .build();

  private final MimeMessageBuilder builder;

  Mail(MimeMessageBuilder builder) {
    this.builder = builder;
  }

  public static MailBuilder builder() {
    return new Start();
  }

  @Override
  public Equality isEqualTo(Object that) {
    return TESTER.test(this, that);
  }

  void deliver(Session session) {
    try {
      Transport transport = session.getTransport();
      transport.connect();

      MimeMessage message = builder.toMimeMessage(session);
      transport.sendMessage(message, message.getAllRecipients());

      transport.close();
    } catch (NoSuchProviderException e) {
      Throwables.propagate(e);
    } catch (MessagingException e) {
      Throwables.propagate(e);
    } catch (UnsupportedEncodingException e) {
      Throwables.propagate(e);
    }
  }

  private static class Start extends AbstractMailBuilder {

    @Override
    public MimeMessage toMimeMessage(Session session) throws MessagingException, UnsupportedEncodingException {
      throw new UnsupportedOperationException();
    }

  }

}