/* © SRSoftware 2025 */
package de.srsoftware.umbrella.core.model;

import static de.srsoftware.umbrella.core.constants.Field.*;
import static java.text.MessageFormat.format;

import de.srsoftware.tools.Mappable;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

public class Property implements Mappable {
	long id;
	String name;
	Object value;
	String unit;

	public Property(long id, String name, Object value, String unit) {
		this.id = id;
		this.name = name;
		this.value = value;
		this.unit = unit;
	}

	public long id(){
		return id;
	}

	public String name(){
		return name;
	}

	public static Property of(ResultSet rs) throws SQLException {
		var id = rs.getLong(ID);
		var name = rs.getString(NAME);
		Object value = null;
		try {
			value = rs.getObject(VALUE);
		} catch (SQLException e){
			if (!e.getMessage().contains("no such column")) throw e;
		}
		var unit = rs.getString(UNIT);
		return new Property(id, name, value, unit);
	}

	@Override
	public Map<String, Object> toMap() {
		var map = new HashMap<String,Object>();
		map.put(ID,id);
		if (name  != null) map.put(NAME,name);
		if (value != null) map.put(VALUE,value);
		if (unit  != null) map.put(UNIT,unit);
		return map;
	}

	@Override
	public String toString() {
		return format("{0} ({1} = {2}{3})",getClass().getSimpleName(),name,value,unit==null?"":" "+unit);
	}

	public String unit(){
		return unit;
	}

	public Object value(){
		return value;
	}

	public Property value(Object newVal){
		value = newVal;
		return this;
	}
}
