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.webmaster3.core.semantic.semantic_document_parser.location.EntityLocation;

import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

public class MFExceptions extends MFException {

    final private Set<MFException> exs;
//    final private String prefixKey;

    public MFExceptions(@NotNull final String mfName) {
        super(mfName);
        exs = new LinkedHashSet<MFException>();
    }

    public MFExceptions(@NotNull final String name, String prefixKey) {
        super(name);
        exs = new LinkedHashSet<MFException>();
    }

    public MFExceptions(@NotNull final String name, EntityLocation location) {
        super(name);
        exs = new LinkedHashSet<MFException>();

    }

    public MFExceptions(@NotNull final String name, String prefixKey, EntityLocation location) {
        super(name);
        exs = new LinkedHashSet<MFException>();

    }

    public boolean isEmpty() {
        return exs.isEmpty();
    }

    public List<MFException> getExceptionsByTreeView() {
        return Cf.list(exs);
    }

    public void put(final MFException e) {
        exs.add(e);

    }
    public void put(final MFException e, final String prefix) {
//        exs.add(e);
        exs.add(new PrefixMicroformatExceptionWrapper(e,prefix));

    }


    public void put(final MFExceptions e) {
        if (e.isEmpty()) {
            return;
        }
        exs.add(e);
    }

    public List<MFException> getExceptionsByListView() {
        return getExceptionsByListView(new LinkedList<MFException>());
    }

    private List<MFException> getExceptionsByListView(final LinkedList<MFException> exceptions) {
        for (final MFException e : exs) {
            if (e instanceof MFExceptions) {
                ((MFExceptions) e).getExceptionsByListView(exceptions);
            } else {
                exceptions.addLast(e);
            }
        }
        return exceptions;
    }

    @Override
    public String getLocalizedMessage() {
        final StringBuilder sb = new StringBuilder("");
        for (final MFException e : exs) {
            sb.append(e.getLocalizedMessage());
        }
        return sb.toString();
    }

    @Override
    public boolean isCritical() {
        for (final MFException ex : exs) {
            if (ex.isCritical()) {
                return true;
            }
        }
        return false;
    }

    public void concatenate(final MFExceptions other) throws InvalidActionException {
        if (!getMessage().equals(other.getMessage())) {
            throw new InvalidActionException(getMessage() + " != " + other.getMessage());
        }
        exs.addAll(other.getExceptionsByTreeView());
    }

    @Override
    public String getKey() {
        return null;
    }

}
