<?php
/*
 * Copyright (c) 2013, webvariants GbR, http://www.webvariants.de
 *
 * This file is released under the terms of the MIT license. You can find the
 * complete text in the attached LICENSE file or online at:
 *
 * http://www.opensource.org/licenses/mit-license.php
 */

class WV_MailLogger extends sly_Mail {
	private $log;

	private function getLog() {
		if (!$this->log) {
			$line = str_repeat('-', 72);
			$this->log = sly_Log::getInstance('wv-mails');
			$this->log->enableRotation();
			$this->log->setFormat(implode("\n", array(
				'Date   : %date%',
				'From   : %from%',
				'To     : %to%',
				'Subject: %subject%',
				'Headers: %headers%',
				'Params : %params%',
				$line,
				'%message%',
				$line
			)));
		}

		return $this->log;
	}

	public static function register(array $params) {
		return __CLASS__;
	}

	/**
	 * @throws sly_Mail_Exception  when something is wrong
	 * @return boolean             always true
	 */
	public function send() {
		$params = '';

		// do nothing if no one would read it
		if (empty($this->tos)) {
			throw new sly_Mail_Exception('No recipients given.');
		}

		// build recipient
		$to = array_map(array($this, 'buildAddress'), $this->tos);

		// build sender if available
		if (!empty($this->from)) {
			$this->setHeader('From', $this->buildAddress($this->from));
			$params = '-f'.$this->from[0]; // -fmy@sender.com
		}

		// set content type
		$this->setHeader('Content-Type', $this->contentType.'; charset='.$this->charset);

		// prepare headers
		$headers = array();

		foreach ($this->headers as $field => $value) {
			$headers[] = $field.': '.$value;
		}

		$context = array(
			'date'    => date('r'),
			'from'    => $this->headers['from'],
			'to'      => implode("\n         ", array_unique($to)),
			'subject' => $this->subject,
			'headers' => implode("\n         ", $headers),
			'params'  => $params
		);

		// log the mail
		$this->getLog()->info($this->body, 1, $context);

		return true;
	}

	/**
	 * @param  array $adress  the address as an arra(mail, name)
	 * @return string         the final adress (only address or address with name)
	 */
	protected function buildAddress($address) {
		list($mail, $name) = $address;

		if (strlen($name) === 0) {
			return $mail;
		}

		return $name.' <'.$mail.'>';
	}
}
