/*
 * This file is part of Nuts Framework.
 * Copyright(C) 2009-2012 Nuts Develop Team.
 *
 * Nuts Framework is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License any later version.
 * 
 * Nuts Framework is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Nuts Framework. If not, see <http://www.gnu.org/licenses/>.
 */
package nuts.core.util.converter;

import java.lang.reflect.Array;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;


public class MapConverter<T extends Map<?,?>> extends AbstractConverter<T> {
	private ConverterFactory factory;
	private Class keyType;
	private Class valType;
	private Converter keyConv;
	private Converter valConv;
	
	public MapConverter(Class<T> type, Class<?> keyType, Class<?> valType, ConverterFactory factory) {
		super(type);
		
		this.factory = factory;
		this.keyType = keyType;
		this.valType = valType;
	}

	@Override
	@SuppressWarnings("unchecked")
	protected T convertValue(Object value) {
		if (keyConv == null) {
			keyConv = factory.getConverter(keyType);
		}
		if (valConv == null) {
			valConv = factory.getConverter(valType);
		}
		

		Map map = createObject();
		if (value.getClass().isArray()) {
			int size = Array.getLength(value);

			for (int i = 0; i < size; i++) {
				Object v = Array.get(value, i);
				if (v instanceof Entry) {
					Object key = keyConv.convert(((Entry)v).getKey());
					Object val = keyConv.convert(((Entry)v).getValue());
					map.put(key, val);
				}
				else {
					v = keyConv.convert(v);
					map.put(v, null);
				}
			}
		}
		else if (value instanceof Map) {
			for (Entry en : (Set<Entry>)((Map)value).entrySet()) {
				Object key = keyConv.convert(en.getKey());
				Object val = keyConv.convert(en.getValue());
				map.put(key, val);
			}
		}
		else if (value instanceof Iterable) {
			Iterator it = ((Iterable)value).iterator();
			while (it.hasNext()) {
				Object v = it.next();
				if (v instanceof Entry) {
					Object key = keyConv.convert(((Entry)v).getKey());
					Object val = keyConv.convert(((Entry)v).getValue());
					map.put(key, val);
				}
				else {
					v = keyConv.convert(v);
					map.put(v, null);
				}
			}
		}
		else {
			Object v = keyConv.convert(value);
			map.put(v, null);
		}
		return (T)map; 
	}
}
