package ru.yandex.autotests.directapi.matchers.beans;

import net.minidev.json.JSONArray;
import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
import org.hamcrest.Factory;
import org.hamcrest.Matcher;

import ru.yandex.autotests.direct.utils.beans.BeanWrapper;

/**
 * Created with IntelliJ IDEA.
 * User: mariabye
 * Date: 25.03.13
 * Time: 18:41
 * To change this template use File | Settings | File Templates.
 */
public class AnyItem extends BaseMatcher {

    private final Matcher elementMatcher;

    public AnyItem(Matcher elementMatcher) {
        this.elementMatcher = elementMatcher;
    }

    @Override
    public boolean matches(Object o) {
        Object[] items;
        if (!(o instanceof Object[]) && !(o instanceof JSONArray)) {
            items = new Object[]{o};
        } else if (o instanceof JSONArray) {
            items = ((JSONArray) o).toArray();
        } else {
            items = (Object[]) o;
        }
        for (Object item : items) {
            if (item instanceof BeanWrapper) {
                item = ((BeanWrapper) item).getBean();
            }
            if (elementMatcher.matches(item)) {
                return true;
            }
        }
        return false;
    }

    public void describeTo(Description description) {
        description
                .appendText("Collection contains bean that ")
                .appendDescriptionOf(elementMatcher);
    }

    @Factory
    public static Matcher anyItem(Matcher elementMatcher) {
        return new AnyItem(elementMatcher);
    }
}
