/*-
 * ~~~~~~licensing~~~~~~
 * test-producers
 * ==========
 * Copyright (C) 2020 - 2022 EmDev LLC
 * ==========
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ~~~~~~/licensing~~~~~~
 */
package ru.entaxy.platform.core.producer.executor.generationmodel;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;

public class GeneratedHeaders {

	public static final String HEADERS_PROPERTY = "##headers";
	
	public static GeneratedHeaders getHeaders(Map<String, Object> properties) {
		if (!properties.containsKey(HEADERS_PROPERTY))
			properties.put(HEADERS_PROPERTY, new GeneratedHeaders());
		return (GeneratedHeaders)properties.get(HEADERS_PROPERTY);
	}
	
	Map<String, Object> headers = new HashMap<>();
	
	public void set(String name, Object value) {
		this.headers.put(name, value);
	}
	
	public void append(String name, Object value) {
		if (!headers.containsKey(name))
			headers.put(name, new LinkedList<Object>());
		else {
			Object obj = headers.get(name);
			if (!(obj instanceof List<?>)) {
				List<Object> list = new LinkedList<Object>();
				list.add(obj);
			}
		}
		List<Object> list = (List<Object>)headers.get(name);
		list.add(value);
	}
	
	public Map<String, String> getAsStringMap(){
		Map<String, String> result = new HashMap<>();
		for (Entry<String, Object> entry: headers.entrySet())
			result.put(entry.getKey(), getValueAsString(entry.getValue()));
		return result;
	}
	
	protected String getValueAsString(Object value) {
		if (value == null)
			return "";
		if (value instanceof Map<?,?>)
			return getMapValueAsString((Map<?,?>)value);
		if (value instanceof List<?>)
			return getListValueAsString((List)value);
		return value.toString();
	}
	
	protected String getMapValueAsString(Map<?,?> value) {
		return "[" + value.entrySet().stream().filter(e -> e.getKey()!=null)
			.map(e -> e.getKey().toString()+"="+getValueAsString(e.getValue()))
			.collect(Collectors.joining(",")) + "]";
	}
	
	protected String getListValueAsString(List<?> value) {
		return value.stream().map(obj->getValueAsString(obj)).collect(Collectors.joining(","));
	}
}
