<?php

namespace Eater\Glim\Service;

use Eater\Glim\Model\EmailMessage;
use Eater\Glim\Model\User as UserModel;
use Nette\Mail\IMailer;
use Nette\Mail\Message;

class Mail extends Main
{
    /**
     * @param UserModel $user
     * @param string $template
     * @param array $context
     */
    public function sendFromSystem(UserModel $user, $template, $context)
    {
        $message = $this->createEmailMessage($template, $context);
        $message->setRecipientEmailAddress($user->getEmailAddressRelatedByEmail());
        $message->save();

        $this->sendEmailMessage($message);
    }

    /**
     * @param string $template
     * @param array $context
     * @return EmailMessage
     */
    public function createEmailMessage($template, $context) {
        $message = new EmailMessage();

        /** @var \Twig_Environment $twig */
        $twig = $this->get('twig');

        $txt = $twig->render($template, $context);

        list($subject, $contents) = explode('===', $txt, 2);

        $message->setSubject(trim($subject));
        $message->setContents(trim($contents));

        return $message;
    }

    /**
     * @param EmailMessage $emailMessage
     */
    public function sendEmailMessage(EmailMessage $emailMessage)
    {
        $mail = new Message();
        $mail->setSubject($emailMessage->getSubject());
        $mail->setBody($emailMessage->getContents());
        $mail->setFrom($emailMessage->getSenderEmail(), $emailMessage->getSenderName());
        $mail->setReturnPath($emailMessage->getSenderEmail());
        
        $mail->addTo($emailMessage->getRecipientEmail(), $emailMessage->getRecipientName());
        /** @var IMailer $sender */
        $sender = $this->get('mail-sender');

        $sender->send($mail);
    }
}