package ru.yandex.direct.http.smart.parameters;

import java.util.Map;

import javax.annotation.Nullable;

import ru.yandex.direct.http.smart.converter.RequestBodyConverter;
import ru.yandex.direct.http.smart.core.SmartRequestBuilder;

public class HeaderMapParameterHandler<T> implements ParameterHandler<Map<String, T>> {
    private final RequestBodyConverter<T> valueConverter;

    public HeaderMapParameterHandler(RequestBodyConverter<T> valueConverter) {
        this.valueConverter = valueConverter;
    }

    @Override
    public void apply(SmartRequestBuilder builder, @Nullable Map<String, T> value) {
        if (value == null) {
            throw new IllegalArgumentException("Header map was null.");
        }

        for (Map.Entry<String, T> entry : value.entrySet()) {
            String headerName = entry.getKey();
            if (headerName == null) {
                throw new IllegalArgumentException("Header map contained null key.");
            }
            T headerValue = entry.getValue();
            if (headerValue == null) {
                throw new IllegalArgumentException(
                        "Header map contained null value for key '" + headerName + "'.");
            }
            builder.addHeader(headerName, valueConverter.convert(headerValue).asString());
        }
    }
}
