package ru.yandex.webmaster3.core.semantic.semantic_document_parser.validators;

import ru.yandex.common.util.xml.Xmler;
import ru.yandex.webmaster3.core.semantic.semantic_document_parser.microdata.MicrodataUtils;
import ru.yandex.webmaster3.core.semantic.semantic_document_parser.microdata.classificator.ItemTypeClassificator;
import ru.yandex.webmaster3.core.semantic.semantic_document_parser.microdata.data.ComplexMicrodata;
import ru.yandex.webmaster3.core.semantic.semantic_document_parser.microdata.data.Microdata;
import ru.yandex.webmaster3.core.semantic.semantic_document_parser.microdata.exceptions.ConfigurableMicrodataValidatorExceptionSerializer;
import ru.yandex.webmaster3.core.semantic.semantic_document_parser.microdata.exceptions.MicrodataValidatorException;
import ru.yandex.webmaster3.core.semantic.semantic_document_parser.microdata.validators.MicrodataValidator;

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

/**
 * Created by IntelliJ IDEA.
 * User: rasifiel
 * Date: 11/14/11
 * Time: 12:17 AM
 */
public class MicrodataCardsValidator implements CardsValidator {

    private List<MicrodataValidator> microdataValidators;

    public void setMicrodataValidators(final List<MicrodataValidator> microdataValidators) {
        this.microdataValidators = microdataValidators;
    }

    @Override
    public List<Xmler.Tag> process(final String content, final String url, final MessageStorage messageStorage, final String lang) {
        final ConfigurableMicrodataValidatorExceptionSerializer microdataValidatorExceptionSerializer = new ConfigurableMicrodataValidatorExceptionSerializer(messageStorage,lang);
        final List<Xmler.Tag> tags = new LinkedList<Xmler.Tag>();
        final List<Microdata> microdatas = MicrodataUtils.extractMD(content, url, true, false);
        List<MicrodataValidatorException> exceptions = new LinkedList<MicrodataValidatorException>();
        for (final Microdata element : microdatas) {
            if (element instanceof ComplexMicrodata) {
                final String baseItemtype = ((ComplexMicrodata) element).getType();
                final String type = MicrodataUtils.extractType(baseItemtype);
                final String rootType = ItemTypeClassificator.getRoot(type);
                if (ItemTypeClassificator.isSupported(rootType)) {
                    if (microdataValidators != null) {
                        for (final MicrodataValidator validator : microdataValidators) {
                            exceptions.addAll(validator.validate(element));
                        }
                    }
                    tags.add(MicrodataUtils.toXml(element, rootType.toLowerCase(), false));
                } else {
                    tags.add(MicrodataUtils.toXml(element, null, false));
                }
            }
        }
        for (final MicrodataValidatorException ex : exceptions) {
            tags.add(microdataValidatorExceptionSerializer.toXml(ex));
        }
        return tags;
    }
}
