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

import ru.yandex.webmaster3.core.semantic.semantic_document_parser.microformats.data.MFAnyData;
import ru.yandex.webmaster3.core.semantic.semantic_document_parser.microformats.data.MicroformatData;
import ru.yandex.webmaster3.core.semantic.semantic_document_parser.microformats.data.property_types.DatetimeData;
import ru.yandex.webmaster3.core.semantic.semantic_document_parser.microformats.exceptions.*;
import ru.yandex.webmaster3.core.semantic.semantic_document_parser.microformats.spec.MFProperty;
import ru.yandex.webmaster3.core.semantic.semantic_document_parser.microformats.spec.Microformat;
import ru.yandex.webmaster3.core.semantic.semantic_document_parser.validators.ISO8601Validator;

import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: rasifiel
 * Date: 6/29/12
 * Time: 10:32 PM
 */
public class DatetimeValidator implements MicroformatValidator {
    @Override
    public MFExceptions validate(final MicroformatData data) {
        final MFExceptions exs = new MFExceptions(data.getName());
        final Microformat spec = data.getSpec();
        try {
            for (final MFProperty prop : spec.getProperties()) {
                List<MFAnyData> values = data.getDataAsList(prop.getName());
                for (final MFAnyData value : values) {
                    if (value instanceof DatetimeData) {
                        if (!ISO8601Validator.validate(((DatetimeData) value).datetime)) {
                            MFException ex = new DatetimeFormatException(
                                    ((DatetimeData) value).datetime + "$$" + prop.getName(), prop.getLocation());
                            ex.setCard(data);
                            exs.put(ex);
                        }
                    } else if (value instanceof MicroformatData) {
                        exs.put(validate((MicroformatData) value));
                    }
                }
            }
            return exs;
        } catch (InvalidActionException e) {
            throw new RuntimeException(e);
        }
    }

}
