package devices.DHT;

import anywheresoftware.b4a.BA;
import anywheresoftware.b4a.keywords.DateTime;

@BA.ShortName("DHT_Data")
public class DHT_Data {

	private long tick;
	private double temp;
	private double hum;
	private boolean isvalid;
	
	public DHT_Data() {
		tick = DateTime.getNow();
		temp = -1;
		hum = -1;
		isvalid = false;
	}
	
	public DHT_Data(long raw_value){
		tick = DateTime.getNow();
		BA.Log("Raw Data = "+raw_value);
		byte checkbyte = ((byte) raw_value);
		int T_koma = ((byte) (raw_value>>8)) & 0xFF;
		int T_int = ((byte) raw_value >> 16) & 0xFF;
		int H_koma = ((byte) raw_value >> 24) & 0xFF;
		int H_int = ((byte) raw_value >> 32) & 0xFF;
		
		byte checkvalue = (byte)(T_koma + T_int + H_koma + H_int);
		isvalid = (checkbyte == checkvalue ? true:false);
		temp = (double)T_int + (T_koma / 10.0);
		hum = (double)H_int + (H_koma / 10.0);
		
	}
	
	DHT_Data(double temperature, double humidity){
		tick = DateTime.getNow();
		this.temp = temperature;
		this.hum = humidity;
		if (this.temp> 0) {
			if (this.hum > 0) {
				this.isvalid = true;				
			}
		}
	}
	
	/**
	 * Get Temperature
	 * @return -1 if invalid
	 */
	public double getTemperature() {
		if (isvalid) {
			return this.temp;			
		} else return -1;
	}
	
	/**
	 * Get Temperature in String
	 * @return N/A if not available
	 */
	public String getTemperatureString() {
		if (isvalid) {
			return temp+" C";
		} else return "N/A";
	}
	
	/**
	 * Get Humidity in String
	 * @return N/A if not available
	 */
	public String getHumidityString() {
		if (isvalid) {
			return hum+" %";
		} else return "N/A";
	}
	
	/**
	 * Get Humidity
	 * @return -1 if invalid
	 */
	public double getHumidity() {
		if (isvalid)
			return this.hum;
		else return -1;
	}
	
	/**
	 * Get Measurement Tick time
	 * @return tick in long
	 */
	public long getMeasurementTick() {
		return this.tick;
	}
	
	/**
	 * Get Date of Measurement
	 * @return Date in string
	 */
	public String getMeasurement_Date() {
		return DateTime.Date(tick);
	}
	
	/**
	 * Get Time of Measurement
	 * @return Time in String
	 */
	public String getMeasurement_Time() {
		return DateTime.Time(tick);
	}
	
	/**
	 * Check if measurement data is valid
	 * @return true if valid
	 */
	public boolean getIsValidMeasurement() {
		return isvalid;
	}
	
	/**
	 * Get Summary in String
	 */
	public String toString() {
		StringBuilder str = new StringBuilder();
		str.append("[").append(getMeasurement_Date()).append(" ").append(getMeasurement_Time()).append("] ");
		str.append("Temperature:").append(this.temp).append(" C, ");
		str.append("Humidity:").append(this.hum).append(" %, ");
		str.append("Valid:").append(this.isvalid);
		return str.toString();
	}
	
}
