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

import org.jetbrains.annotations.NotNull;
import ru.yandex.common.util.collections.Cf;
import ru.yandex.common.util.xml.Xmler;
import ru.yandex.webmaster3.core.semantic.semantic_document_parser.tanker.LanguageContext;

import java.util.LinkedList;
import java.util.List;

import static ru.yandex.common.util.xml.Xmler.attribute;
import static ru.yandex.common.util.xml.Xmler.unescapedTag;

/**
 * Created by IntelliJ IDEA.
 * User: rasifiel
 * Date: 1/20/12
 * Time: 2:54 AM
 */
public class TankerMFExceptionSerializer implements MFExceptionSerializer {

    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;

    static final public String startBoldTag = "<b>";
    static final public String endBoldTag = "</b>";
    static final public String separator = ".";
    static final public String altSeparator = "\\|";


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

    @Override
    public List<Xmler.Tag> toXML(@NotNull final MFException ex) {
        return toXML(ex,"");
    }

    protected List<Xmler.Tag> toXML(final MFException ex, final String prefix) {
        if (ex instanceof MFExceptions) {
            return toXML((MFExceptions) ex, prefix);
        }
        final StringBuilder sb = new StringBuilder();
        sb.append(ex.isCritical() ? error : warning);
        final String message = context.getValue(ex.getKey()).getString();
        final String procMessage = new StringBuilder().append(startBoldTag).append(
                ex.getMessage().replaceAll(altSeparator, alt_word)).append(endBoldTag).toString();
        sb.append(message.replaceFirst("%s",procMessage));
        sb.append(" ");
        final Xmler.Tag result = unescapedTag("error", attribute("card_hash", ex.getCard().number).and(attribute("error_code",ex.getKey())), sb.toString());
        return Cf.list(result);
    }

    protected List<Xmler.Tag> toXML(final MFExceptions exceptions, final String prefix) {
        final String newPrefix =
                prefix + (exceptions.getMessage().isEmpty() ? "" : exceptions.getMessage() + separator);
        final List<Xmler.Tag> result = new LinkedList<Xmler.Tag>();
        for (final MFException exception : exceptions.getExceptionsByTreeView()) {
            result.addAll(toXML(exception, newPrefix));
        }
        return result;
    }

}
