package org.onetwo.boot.core.web.view;

import java.util.Map;
import java.util.Map.Entry;

import org.onetwo.boot.core.web.utils.ModelAttr;
import org.onetwo.common.data.AbstractDataResult.SimpleDataResult;
import org.onetwo.common.data.DataResult;
import org.onetwo.common.data.DataResultWrapper;
import org.onetwo.common.spring.mvc.utils.DataResults;
import org.onetwo.common.spring.mvc.utils.DataResults.MapResultBuilder;
import org.springframework.validation.BindingResult;

/**
 * @author wayshall
 * <br/>
 */
public class DefaultDataResultWrapper implements DataResultWrapper {
	
	
	@Override
	public Object wrapResult(final Object data) {
		Object newData = wrapAsDataResultIfNeed(data);
		return newData;
	}
	
	protected DataResult<?> wrapAsDataResultIfNeed(Object result){
		if(DataResult.class.isInstance(result)){
			return (DataResult<?>)result;
		}
		if(Map.class.isInstance(result)){
			@SuppressWarnings("unchecked")
			MapResultBuilder dataResult = createMapResultBuilder((Map<String, Object>) result);
			return dataResult.build();
		}else{
			SimpleDataResult<Object> dataResult = SimpleDataResult.success("success", result);
			return dataResult;
		}
	}
	
	private MapResultBuilder createMapResultBuilder(Map<String, Object> map){
		MapResultBuilder dataResult = DataResults.map().success();
		for(Entry<String, Object> entry : map.entrySet()){
			if(BindingResult.class.isInstance(entry.getValue())){
				BindingResult br = (BindingResult) entry.getValue();
				if(br.hasErrors()){
					dataResult.error();
				}
				
			}else if(ModelAttr.MESSAGE.equalsIgnoreCase(entry.getKey())){
				dataResult.success(entry.getValue().toString());
				
			}else if(ModelAttr.ERROR_MESSAGE.equalsIgnoreCase(entry.getKey())){
				dataResult.error(entry.getValue().toString());
				
			}else{
				dataResult.put(entry.getKey(), entry.getValue());
			}
		}
		return dataResult;
	}

}

@@ -1642,32 +1642,106 @@
 ().toString());%0A
+%09%09%09%09//%E5%8F%AA%E8%BF%94%E5%9B%9Emessage%EF%BC%8C%E6%B8%85%E7%A9%BAdata%0A%09%09%09%09dataResult.data(null);%0A%09%09%09%09return dataResult;%0A
 %09%09%09%09%0A%09%09%09%7Delse if
@@ -1847,24 +1847,98 @@
 oString());%0A
+%09%09%09%09//%E5%8F%AA%E8%BF%94%E5%9B%9Emessage%EF%BC%8C%E6%B8%85%E7%A9%BAdata%0A%09%09%09%09dataResult.data(null);%0A%09%09%09%09return dataResult;%0A
 %09%09%09%09%0A%09%09%09%7Dels

fix data result wrapper