<?php

namespace Velis\Mail\Transport;

use Zend\Mail\Protocol\Smtp as ZendSmtpProtocol;
use Zend\Mail\Transport\Smtp as ZendSmtp;
use Zend\Mail\Message;

/**
 * Smtp transport extension
 * @author Olek Procki <olo@velis.pl>
 */
class Smtp extends ZendSmtp
{
    /**
     * Connect the connection, and pass it helo
     *
     * @return ZendSmtp
     */
    protected function connect()
    {
        if (!$this->connection instanceof ZendSmtpProtocol) {
            return $this->lazyLoadConnection();
        }

        $options = $this->getOptions();
        $connectionClass = $options->getConnectionClass();

        $this->connection->connect();

        $this->connectedTime = time();

        // disabled for oauth2 because helo should be sent before auth
        if ($connectionClass !== 'xoauth2') {
            $this->connection->helo($options->getName());
        }

        return $this->connection;
    }

    /**
     * Prepare body string from message
     *
     * @param  Message $message
     * @return string
     */
    protected function prepareBody(Message $message)
    {
        $body = parent::prepareBody($message);
        return preg_replace("#(?<!\r)\n#si", "\r\n", $body);
    }


    /**
     * Prepare header string from message
     *
     * @param  Message $message
     * @return string
     */
    protected function prepareHeaders(Message $message)
    {
        $headers = parent::prepareHeaders($message);
        return preg_replace("#(?<!\r)\n#si", "\r\n", $headers);
    }
}
