/*
 * Copyright 2012 s_wolff.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.aegee.runanddine.mail;

import com.xfltr.hapax.Template;
import com.xfltr.hapax.TemplateDictionary;
import com.xfltr.hapax.TemplateException;
import java.io.Serializable;
import java.util.List;
import java.util.Map;

/**
 * RenderContext for AbstractMails
 * @author s_wolff
 */
public abstract class MailRenderContext implements Serializable {

    private TemplateDictionary dict;
    //private Map<String, String> context;

    public MailRenderContext(Map<String, String> context) {
        //this.context = context;
        dict = TemplateDictionary.create();
        for (String key : context.keySet()) {
            dict.put(key, context.get(key));
        }
    }

    /**
     * This method renders a key according to the internal render context. If the
     * given key is not available for rendering <code>null</code> is returned.
     * @param key the key that shall be rendered
     * @return the value for the given key, or <code>null</code> if the given key
     * does not exist
     */
    protected String renderKey(String key) {
        return this.dict.get(key);
    }

    /**
     * 
     * @return 
     */
    protected List<String> getKeys() {
        return this.dict.getKeys();
    }

    /**
     * Provides the render context of this object. Note that the <code>MailRenderContext</code>
     * is immutable. Thus changes of the returned map will not reflect to the
     * internal render context.
     * @return 
     */
    protected Map<String, String> getDict() {
        return this.dict.getDict();
    }

    /**
     * Renders a given text.
     * @param text
     * @return 
     */
    public String render(String text) {
        try {
            Template tmpl = Template.parse(text);
            return tmpl.renderToString(this.dict);
        } catch (TemplateException e) {
            throw new RenderException(e.getMessage());
        }
    }

    public Mail render(Mail mail, boolean renderSubject) {
        String newSubject = renderSubject ? this.render(mail.getSubject()) : mail.getSubject();
        String newContent = this.render(mail.getContent());
        return new Mail(newSubject, mail.getTo(), mail.getFrom(), newContent);
    }
}