<?php

Prado::using('System.I18N.Globalization');
Prado::using('Application.mail.Mailer');
Prado::using('Application.mail.MailTemplate');
Prado::using('Application.mail.MailTemplateTranslator');
Prado::using('Application.model.MailQueue');

class MailModule extends TModule {

    private $_configPath;
    private $_config;

    private $_queuedTemplates = [];

    private $_templatePath;
    private static $_templateExtension = 'html';
    private $_templateCacheSubpath = 'mail';
    private static $_templateTranslationCatalogue = 'messages';

    public function init($xml) {
        parent::init($xml);
        if ($queueTemplates = $xml->getElementByTagName('mail-queue')) {
            foreach ($queueTemplates->getElementsByTagName('template') as $template) {
                $this->_queuedTemplates[] = $template->Attributes['id'];
            }
        }
    }

    public function setConfigPath(string $configPath) {
        $this->_configPath = TPropertyValue::ensureString($configPath);
        $this->_config = json_decode(
            file_get_contents(
                Prado::getPathOfNamespace($this->_configPath, '.json')
            )
        );
    }

    public function getConfig() {
        return $this->_config;
    }

    public function setTemplatePath(string $templatePath) {
        $this->_templatePath = Prado::getPathOfNamespace(
            TPropertyValue::ensureString($templatePath)
        );
    }

    public function getTemplatePath() {
        if (!file_exists($this->_templatePath)
            || !is_dir($this->_templatePath)) {
            throw new TConfigurationException(
                Prado::localize(
                    'Invalid mail template path'
                )
            );
        }
        return $this->_templatePath;
    }

    public function setCachePath(string $cachePath) {
        $this->templateCacheSubpath = TPropertyValue::ensureString($cachePath);
    }

    public function getCachePath() {
        $cachePath = $this->getApplication()->getRuntimePath()
            . DIRECTORY_SEPARATOR
            . $this->_templateCacheSubpath;
        if (!file_exists($cachePath)) {
            mkdir($cachePath);
        } else {
            if (!is_dir($cachePath)
                || !is_writable($cachePath)) {
                throw new TConfigurationException(
                    Prado::localize(
                        'Template cache path must be a writable directory'
                    )
                );
            }
        }
        return $cachePath;
    }

    public function setTemplateExtension(string $ext) {
        self::$_templateExtension = TPropertyValue::ensureString($ext);
    }

    public function getTemplateExtension() {
        return self::$_templateExtension;
    }

    public function setTranslationCatalogue(string $ext) {
        self::$_templateTranslationCatalogue = TPropertyValue::ensureString($ext);
    }

    public function getTranslationCatalogue() {
        return self::$_templateTranslationCatalogue;
    }

    private static $_translator;

    private static function _getTranslator() {
        if (!isset(self::$_translator)) {
            self::$_translator = new MailTemplateTranslator(
                self::$_templateTranslationCatalogue
            );
        }
        return self::$_translator;
    }

    public function getTemplate(string $templateID, string $language='') {
        $template = new MailTemplate($templateID . '.' . $this->TemplateExtension);

        $template->setOutputMode(PHPTAL::HTML5);
        $template->setTemplateRepository($this->_templatePath);
        $template->setPhpCodeDestination($this->CachePath);

        $template->toggleImmediate(!in_array($templateID, $this->_queuedTemplates));

        $translator = self::_getTranslator();
        $translator->setLanguage($language);
        $template->setTranslator($translator);

        return $template;
    }

    public function getMailer() {
        if (!$this->_config) {
            throw new TConfigurationException(
                Prado::localize(
                    'Mailer not configured'
                )
            );
        }
        $mailer = new Mailer();
        $mailer->configure($this);
        return $mailer;
    }

    public function queueMail(string $subject, string $body, string $rcptMail, string $rcptName) {
        $queue = new MailQueue();
        $queue->Subject = $subject;
        $queue->HtmlBody = $body;
        $queue->TextBody = strip_tags($body);
        $queue->RecipientName = $rcptName;
        $queue->RecipientMail = $rcptMail;
        $queue->CreateTime = date('Y-m-d H:i:s');
        return $queue->save();
    }

}

?>