package jp.ac.naka.ec.sensor;

import jp.ac.naka.ec.Location;

public class SensorDataImpl implements SensorData {

	String id;
	Location loc;
	Device device;
	long ttl = 60;
	String measure;
	DataType type = DataType.String;
	
	String data, dataName;
	
	public Device getDevice() {
		return device;
	}

	public String getName() {
		return id;
	}

	public Location getLocation() {
		return loc;
	}


	public long getTTL() {
		return ttl;
	}

	public void setDevice(Device device) {
		this.device = device;
	}

	public void setName(String id) {
		this.id = id;
	}

	public void setLocation(Location loc) {
		this.loc = loc;
	}


	public void setTTL(long ttl) {
		this.ttl = ttl;
	}

	
	public DataType getDataType() {
		return type;
	}
	
	public void setDataType(DataType dataType) {
		if (dataType == null)
			return;
		this.type = dataType;
	}
	
	public String getMeasure() {
		return measure;
	}
	
	public void setMeasure(String measure) {
		this.measure = measure;
	}
	public CharSequence toXML() {
		return toXML("");
	}

	public CharSequence toXML(String padding) {
		StringBuilder sb = new StringBuilder();
		
		sb.append(addPadding("<sensor name=\"", padding));
		sb.append(id);
		sb.append("\" ttl=\"");
		sb.append(ttl);
		sb.append("\">\r\n");
		
		// device
		if(device != null)
			sb.append(addPadding(device.toXML(padding), padding+"\t"));
		else
			sb.append(addPadding("\t<device />\r\n" , padding));
		
		// location
		if (loc != null) {
			sb.append(loc.toXML(padding + "\t"));
		} else {
			//sb.append(addPadding("<location />\r\n", padding));
		}
		
		// data
		sb.append (addPadding("\t<data ", padding));
		if (dataName != null) {
			sb.append (" name=\"");
			sb.append(dataName);
			sb.append("\" ");
		}
		sb.append("type=\"");
		sb.append((type != null) ? type.toString() : "Unknown");
		sb.append("\" measure=\"");
		sb.append((measure != null) ? measure : "");
		sb.append("\">");
		sb.append(data);
		sb.append("</data>\r\n");
		sb.append(padding);
		sb.append("</sensor>\r\n");
		return sb.toString();
	}
	
	private String addPadding(String str, String padding) {
		return padding + str;
	}
	
	public void setData(String data) {
		this.data = data;
	}
	
	public Object getData () {
		if (type == null || data == null)
			return data;
		Object ret = null;
		try {
			switch (type) {
			case Integer : ret = Integer.valueOf(data); break;
			case Float : ret = Float.valueOf(data); break;
			case Double : ret = Double.valueOf(data);break;
			case String : ret = data;
			}
		} catch (NumberFormatException e) {
			e.printStackTrace();
		}
		return ret;
	}

	public static void main(String[] args) {
		SensorData s = new SensorDataImpl();
		s.setName("hoge");
		s.setDataName("moxa");
		s.setDataType(DataType.Float);
		s.setData("10");
		s.setLocation(new Location("hogehoge", "20.0", "30.0"));
		System.out.println(s.toXML());
	}
	

	public String getDataName() {
		return dataName;
	}

	public void setDataName(String dataName) {
		this.dataName = dataName;
	}
}
