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

import ru.yandex.common.util.functional.Filter;
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.data.TextMicrodata;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: rasifiel
 * Date: 8/6/11
 * Time: 12:18 PM
 * To change this template use File | Settings | File Templates.
 */
public class MicrodataFilter implements Filter<Microdata> {

    private final List<String> fieldsDef;

    public MicrodataFilter(final List<String> fieldsDef) {
        this.fieldsDef = new ArrayList<String>(fieldsDef);
    }

    @Override
    public boolean fits(final Microdata microdata) {
        for (final String field : fieldsDef) {
            final String[] parts = field.split("\\.");
            if (!fit(microdata, parts, 0)) {
                return false;
            }
        }
        return true;
    }

    private static boolean fit(final Microdata microdata, final String[] fieldParts, final int from) {
        if (from >= fieldParts.length) {
            return microdata instanceof TextMicrodata;
        }
        if (microdata instanceof TextMicrodata) {
            return false;
        }
        final ComplexMicrodata complexMicrodata = (ComplexMicrodata) microdata;
        final List<Microdata> fields = complexMicrodata.getPropAsList(fieldParts[from]);
        if (fields == null || fields.isEmpty()) {
            return false;
        }
        for (final Microdata data : fields) {
            if (fit(data, fieldParts, from + 1)) {
                return true;
            }
        }
        return false;
    }
}
