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

import ru.yandex.common.util.collections.Cf;
import ru.yandex.common.util.functional.Function;
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.MicrodataValidatorException;
import ru.yandex.webmaster3.core.semantic.semantic_document_parser.microdata.exceptions.UnsupportedCountryMicrodataValidatorException;
import ru.yandex.webmaster3.core.semantic.semantic_document_parser.struct_data.Address;
import ru.yandex.webmaster3.core.semantic.semantic_document_parser.struct_data.Organization;
import ru.yandex.webmaster3.core.semantic.semantic_document_parser.struct_data.StructuredDataTransformers;

import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by IntelliJ IDEA.
 * User: rasifiel
 * Date: 12/6/11
 * Time: 1:03 AM
 */
public class UnsupportedCountryMicrodataValidator implements MicrodataValidator {

    private Set<String> countries = Collections.emptySet();

    public void setCountries(final List<String> countries) {
        this.countries = new HashSet<String>((new Function<String, String>() {
            @Override
            public String apply(final String arg) {
                return arg.toUpperCase();
            }
        }).map(countries));
    }

    @Override
    public List<MicrodataValidatorException> validate(final Microdata microdata) {
        if (microdata instanceof ComplexMicrodata) {
            ComplexMicrodata microdataCM = (ComplexMicrodata) microdata;
            Organization org = StructuredDataTransformers.fromSchemaOrgOrganization(microdataCM, "http://localhost");
            if (org != null) {
                for (final Address adr : org.getAddresses()) {
                    if (adr.getCountry() != null) {
                        if (countries.contains(adr.getCountry().toUpperCase())) {
                            return Collections.emptyList();
                        }
                    } else {
                        return Collections.emptyList();
                    }
                }
                if (!org.getAddresses().isEmpty()) {
                    return Cf.<MicrodataValidatorException>list(
                            new UnsupportedCountryMicrodataValidatorException(false, "", microdata));
                }
            }
        }
        return Collections.emptyList();
    }
}
