<?php
/**
 * Description of Mailer
 *
 * @author Petter Castro
 */
namespace Tixpro\TUserBundle\Mailer;

use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface;
use Symfony\Component\Routing\RouterInterface;
use Tixpro\TUserBundle\Entity\User;

class Mailer 
{
    protected $mailer;
    protected $router;
    protected $templating;

    public function __construct($mailer, RouterInterface $router, EngineInterface $templating)
    {
        $this->mailer = $mailer;
        $this->router = $router;
        $this->templating = $templating;
    }

    public function sendConfirmationEmailMessage(User $user)
    {
        $template = "TixproTUserBundle:User:email.txt.twig";
        $url = $this->router->generate('login',array(),true);
        $rendered = $this->templating->render($template, array(
            'user' => $user,
            'loginUrl' =>  $url
        ));
        $this->sendEmailMessage($rendered, "mysystem@gmail.com", $user->getEmail());
    }

    public function sendResettingPasswordMessage(User $user)
    {
        $template = "TixproTUserBundle:User:resettingPassword.txt.twig";
        $url = $this->router->generate('login',array(),true);        
        $rendered = $this->templating->render($template, array(
            'user' => $user,
            'loginUrl' => $url
        ));
        $this->sendEmailMessage($rendered, "mysystem@gmail.com", $user->getEmail());
    }

    /**
     * @param string $renderedTemplate
     * @param string $toEmail
     */
    protected function sendEmailMessage($renderedTemplate, $fromEmail, $toEmail)
    {
        // Render the email, use the first line as the subject, and the rest as the body
        $renderedLines = explode("\n", trim($renderedTemplate));
        $subject = $renderedLines[0];
        $body = implode("\n", array_slice($renderedLines, 1));
        
        $message = \Swift_Message::newInstance()
            ->setSubject($subject)
            ->setFrom($fromEmail)
            ->setTo($toEmail)
            ->setBody($body);

        $this->mailer->send($message);
    }
}
