/* ************************************************************************
#
#  DivConq
#
#  http://divconq.com/
#
#  Copyright:
#    Copyright 2012 eTimeline, LLC. All rights reserved.
#
#  License:
#    See the license.txt file in the project's top-level directory for details.
#
#  Authors:
#    * Andy White
#
************************************************************************ */
package divconq.bus;

import divconq.bus.Message;
import divconq.db.DatabaseResult;
import divconq.struct.FieldStruct;
import divconq.struct.RecordStruct;

public class MessageUtil {
	static public Message success(String... flds) {
		Message m = new Message();
		m.setField("Result", 0);
		
		if (flds.length > 0) {
			RecordStruct body = new RecordStruct();
			
			String name = null;
			
			for (String o : flds) {
				if (o == null)
					continue;
				
				if (name != null) {
					body.setField(name, o);
					name = null;
				}
				else {
					name = o;
				}
			}
			
			m.setField("Body", body);
		}
		
		return m;
	}

	public static Message successAlt(Object body) {
		Message m = new Message();
		m.setField("Result", 0);
		m.setField("Body", body);
		return m;
	}
	
	static public Message error(int code, String msg) {
		Message m = new Message();
		m.setField("Result", code);
		m.setField("Message", msg);
		return m;
	}
	
	static public Message error(DatabaseResult ri, int code, String msg) {
		Message m = new Message();
		
		if ((ri != null) && ri.hasErrors()) {
			m.setField("Result", ri.getCode());
			m.setField("Message", ri.getMessage());
		}
		else {
			m.setField("Result", code);
			m.setField("Message", msg);
		}
		
		return m;
	}
	
	static public Message fromElastic(RecordStruct msg) {
		Message m = new Message();
		
		for (FieldStruct fld : msg.getFields()) {
			if (fld == null)
				continue;
			
			String name = fld.getName();
			
			/*
			if ("Attachments".equals(name)) {
				Object alist = fld.getValue();
				
				if (!(alist instanceof Elastic))
					continue;
				
				// TODO consider supporting other types
				for (Object att : ((Elastic)alist).list()) {
					if (!(att instanceof Elastic))
						continue;
					
					try {
						MemoryBuilder mb = new MemoryBuilder();
						((Elastic)att).toBuilder(mb);					
						m.addAttachment(mb);
					}
					catch (Exception x) {
						// TODO
					}
				}
			}
			else {
				Object val = fld.getValue();
				
				if (val != null)
					m.addHeader(name, val.toString());
			}
			*/
			
			m.setField(name, fld.getValue());
		}
		
		return m;
	}
}
