package ru.yandex.webmaster3.core.semantic.semantic_document_parser.struct_data.transformers.impl;

import ru.yandex.common.util.collections.Cu;
import ru.yandex.common.util.functional.PartialFunction;
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.review_business.auto.model.HProduct;
import ru.yandex.webmaster3.core.semantic.semantic_document_parser.struct_data.JsonStructData;
import ru.yandex.webmaster3.core.semantic.semantic_document_parser.struct_data.StructuredDataTransformers;
import ru.yandex.webmaster3.core.semantic.semantic_document_parser.struct_data.transformers.JsonStructDataTransformer;
import ru.yandex.webmaster3.core.semantic.semantic_document_parser.struct_data.wrapper.AggAutoReviewWrapper;

import java.util.List;

import static ru.yandex.webmaster3.core.semantic.semantic_document_parser.microformats.MicroformatsUtils.extractPropertyToList;

/**
 * Created by IntelliJ IDEA.
 * User: rasifiel
 * Date: 13.11.13
 * Time: 6:41
 */
public class AutoReviewFromMicroformatTransformer extends JsonStructDataTransformer {
    @Override
    public JsonStructData transformStruct(final Object o, final String sourceUrl) {
        MicroformatData md = (MicroformatData) o;
        return new AggAutoReviewWrapper(StructuredDataTransformers.fromAutoHReview(md, sourceUrl));
    }

    @Override
    public boolean checkType(final Object o) {
        if (!(o instanceof MicroformatData)) {
            return false;
        }
        MicroformatData md = (MicroformatData) o;
        List<MFAnyData> items = md.getDataAsList("item");
        if (items.isEmpty()) {
            return false;
        }
        return !Cu.mapWhereDefined(new PartialFunction<HProduct, HProduct>() {
            @Override
            public HProduct apply(final HProduct arg) throws IllegalArgumentException {
                if (arg.getCategory().equals("auto")) {
                    return arg;
                }
                throw new IllegalArgumentException();
            }
        }, extractPropertyToList(md, "item", new PartialFunction<MFAnyData, HProduct>() {
            @Override
            public HProduct apply(final MFAnyData arg) throws IllegalArgumentException {
                if (arg instanceof MicroformatData) {
                    return StructuredDataTransformers.fromHProduct((MicroformatData) arg, "http://localhost");
                }
                throw new IllegalArgumentException();
            }
        })).isEmpty();
    }
}
