package ru.yandex.autodoc.wmtools.out.json;

import ru.yandex.autodoc.common.out.json.JsonConvertableUtils;
import ru.yandex.autodoc.common.out.json.JsonValueWriterFactory;
import ru.yandex.autodoc.common.out.json.builder.ContainerBuilder;
import ru.yandex.autodoc.common.out.json.builder.JsonValueBuilder;
import ru.yandex.common.util.json.JsonConvertable;
import ru.yandex.common.util.json.JsonConvertableWithKey;

/**
 * @author avhaliullin
 */
public class WMJsonConvertableUtils extends JsonConvertableUtils {
    public static JsonConvertableWithKey attachKey(final String key, final JsonConvertable convertable) {
        return new JsonConvertableWithKey() {
            @Override
            public String getKey() {
                return key;
            }

            @Override
            public void toJson(StringBuilder storage) {
                convertable.toJson(storage);
            }
        };
    }

    public static <T> JsonConvertableAdapter wrapIterable(final Iterable<T> collection, final JsonValueWriterFactory<T> factory) {
        return new JsonWrapper<Iterable<T>>(collection) {
            @Override
            public <C extends ContainerBuilder> C doWriteValue(JsonValueBuilder<C> builder) {
                return builder.valueArray(collection, factory);
            }
        };
    }

    public static <T> JsonConvertableWithKeyAdapter wrapIterable(final Iterable<T> collection, final JsonValueWriterFactory<T> factory, String key) {
        return new JsonWrapper<Iterable<T>>(collection) {
            @Override
            public <C extends ContainerBuilder> C doWriteValue(JsonValueBuilder<C> builder) {
                return builder.valueArray(collection, factory);
            }
        }.withKey(key);
    }

}
