<?php 

class ActionMailer {
	private static $deliver_prefix = 'send_';
	protected static $message = '';
	protected static $body = array();
	protected static $to = '';
	protected static $cc = '';
	protected static $bcc = '';
	protected static $reply_to = '';
	protected static $from = '';
	protected static $subject = '';	
	protected static $isHTML = true;	
	protected static $config = array();


	private static function load_view($method)
	{
		$class   = strtolower(preg_replace('/(?<=[a-z])([A-Z])/', '_$1', get_class(self::getInstance())));
		$dir     = Slim::config('templates_dir');
		$text    = "{$class}/{$method}.txt";
		$html = "{$class}/{$method}.html";
		
		if (file_exists("{$dir}/{$html}")) {
			$view = $html;
			self::$isHTML = true;
		}
		else if (file_exists("{$dir}/{$text}")) {
			$view = $text;
			self::$isHTML = false;
		}
		else {
			throw new Exception("Couldn't find a view for $class/$method ([$dir/$html] or [$dir/$text] is not found in /$dir directory)");
		}
		
        $template = Slim::config('templates_dir').'/'.$view;
        $h2o = new h2o($template, array());
        self::$message = $h2o->render(self::$body);
        return self::$message;
	}

    final public static function getInstance() {
        static $aoInstance = array();

        $calledClassName = get_called_class();

        if (! isset ($aoInstance[$calledClassName])) {
            $aoInstance[$calledClassName] = new $calledClassName();
        }

        return $aoInstance[$calledClassName];
    }
    
	public static function __callStatic($method, $arguments) {
		self::getInstance()->config();
		$cut = strlen(self::$deliver_prefix);
		if (substr($method, 0, $cut) == self::$deliver_prefix)
		{
			$method = substr($method, $cut);
		}
		if (method_exists(self::getInstance(), $method))
		{
			call_user_func_array(array(self::getInstance(), $method), $arguments);
			if (self::load_view($method) && self::valid())
			{
				if (method_exists(self::getInstance(), 'send')) {
					return call_user_func_array(array(self::getInstance(), 'send'),array()); 
				} else {
					return self::getInstance()->send();
				}
			}
		}
		else
		{
			$class = get_class(self::getInstance());
			exit;
		}
	}
	
	public function config() {
		$class   = preg_replace('/(?<=[a-z])([A-Z])/', '_$1', get_class(self::getInstance()));
		throw new Exception("ActionMailer config is empty. Please define config function in your <pre style='display:inline;'>$class</pre> class.");
	}
	
	function send_postmark() {
		require_once("protocol/postmark.php");
		$postmark = new Postmark(self::$config['api_key'],self::$config['from'],self::$config['reply_to']);
		$success = $postmark->to(self::$to)->subject(self::$subject)->plain_message(self::$message)->send();
		
		return $success;
	}
	
	public function send() {
		return call_user_func_array(array(self::getInstance(), 'send_' . self::$config['protocol']),array()); 
	}

	private static function valid()
	{
		$check = array(self::$to, self::$from, self::$subject, self::$message);

		foreach ($check as $c)
		{
			if (trim($c) == '')
			{
				return FALSE;
			}
		}
		return TRUE;
	}

}
