package ru.yandex.webmaster3.core.semantic.semantic_document_parser.ogp.exception;

import ru.yandex.common.util.xml.Xmler;
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 TankerOGPExceptionSerializer implements OGPExceptionSerializer {

    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 TankerOGPExceptionSerializer(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 OGPException ex) {
        return context.getValue(ex.getKey()).getString();
    }

    private String getWarningWord() {
        return warning;
    }

    private String getErrorWord() {
        return error;
    }

    public String getAltWord() {
        return alt_word;
    }

    @Override
    public Xmler.Tag toXml(final OGPException 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.hashCode()).and(attribute("error_code",ex.getKey())), message.toString());
    }
}
