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

import ru.yandex.common.util.collections.Cf;
import ru.yandex.webmaster3.core.semantic.semantic_document_parser.location.EntityLocation;
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.DeprecatedFieldMicrodataValidatorException;
import ru.yandex.webmaster3.core.semantic.semantic_document_parser.microdata.exceptions.MicrodataValidatorException;

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

/**
 * Created by aleksart on 03.03.15.
 */
public class DeprecatedMicrodataValidator implements MicrodataValidator{

    private final String[] fields;
    private final boolean isCritical;

    public DeprecatedMicrodataValidator(final boolean isCritical, final String... fields) {
        this.isCritical = isCritical;
        this.fields = fields;
    }

    @Override
    public List<MicrodataValidatorException> validate(final Microdata microdata) {
        final List<MicrodataValidatorException> exceptions = new LinkedList<MicrodataValidatorException>();
        for (final String field : fields) {
            final String[] elements = field.split("/");
            List<Microdata> current = Cf.list(microdata);

            for (final String element : elements) {
                List<Microdata> newCurrent = new LinkedList<Microdata>();
                for (final Microdata fieldValue : current) {
                    if (fieldValue instanceof ComplexMicrodata) {
                        newCurrent.addAll(((ComplexMicrodata) fieldValue).getPropAsList(element));
                    }
                }
                current = newCurrent;
                if (current.isEmpty()) {
                    break;
                }
            }
            boolean allEmpty = true;
            for (Microdata element : current) {
                if (!element.toString().trim().isEmpty()) {
                    allEmpty = false;
                    break;
                }
            }
            if (!allEmpty) {
                EntityLocation location = EntityLocation.DEFAULT_LOCATION;
                if(current.size()>1){
                    location = current.get(0).location;
                }
                exceptions.add(new DeprecatedFieldMicrodataValidatorException(isCritical, field, microdata,location));
            }
        }
        return Collections.unmodifiableList(exceptions);
    }
}
