package ru.yandex.webmaster3.core.semantic.semantic_document_parser.rdfa.exceptions;

import ru.yandex.webmaster3.core.semantic.semantic_document_parser.tanker.LanguageContext;

import static ru.yandex.common.util.xml.Xmler.*;

/**
 * Created by IntelliJ IDEA.
 * User: rasifiel
 * Date: 2/26/12
 * Time: 8:54 AM
 */
public class TankerRDFaExceptionSerializer {

    private final LanguageContext context;
    private static final String ALT_WORD = "alt_word";
    private static final String ERROR = "error";
    private static final String WARNING = "warning";
    private final String alt_word;
    private final String error;
    private final String warning;

    public TankerRDFaExceptionSerializer(LanguageContext context) {
        this.context = context;
        alt_word = context.getValue(ALT_WORD).getString();
        error = context.getValue(ERROR).getString();
        warning = context.getValue(WARNING).getString();
    }

    private String getMessage(final RDFaException ex) {
        return context.getValue(ex.getKey()).getString();
    }

    private String getWarningWord() {
        return warning;
    }

    private String getErrorWord() {
        return error;
    }

    public String getAltWord() {
        return alt_word;
    }

    public Tag toXml(final RDFaException ex) {
        final StringBuilder message = new StringBuilder();
        message.append((ex.isCritical) ? getErrorWord() : getWarningWord()).append(" ");
        final String procMessage = ex.message.replaceAll("\\|", getAltWord());
        final StringBuilder msgTagBuilder = new StringBuilder();
        tag("b", procMessage.isEmpty() ? "" : procMessage).toXml(msgTagBuilder);
        final String resultMessage = getMessage(ex).replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("%s",
                msgTagBuilder.toString());
        message.append(resultMessage);
        return unescapedTag("error", attribute("card_hash", ex.card.count).and(attribute("error_code", ex.getKey())),
                message.toString());
    }
}
