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

import static de.srsoftware.umbrella.core.Util.mapMarkdown;
import static de.srsoftware.umbrella.core.constants.Field.*;

import de.srsoftware.umbrella.core.api.Owner;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.json.JSONObject;

public class DbLocation extends Location {
	private Owner owner;
	private Long parentLocationId;
	private String name;
	private String description;
	private String relation; // when added to an item, this field describes the type of the relation
	private Set<String> dirtyFields = new HashSet<>();

	public DbLocation(long id, Owner owner, Long parentLocationId, String name, String description){
		super(id);
		this.owner = owner;
		this.parentLocationId = parentLocationId;
		this.name = name;
		this.description = description;
	}

	public DbLocation clear(){
		dirtyFields.clear();
		return this;
	}

	public String description() {
		return description;
	}

	public boolean isDirty() {
		return !dirtyFields.isEmpty();
	}

	public boolean isDirty(String field){
		return dirtyFields.contains(field);
	}

	public String name() {
		return name;
	}

	public static DbLocation of(ResultSet rs) throws SQLException {
		return new DbLocation(rs.getLong(ID), OwnerRef.of(rs), rs.getLong(PARENT_LOCATION_ID), rs.getString(NAME),rs.getString(DESCRIPTION));
	}

	public Owner owner(){
		return owner;
	}

	public Long parent(){
		return parentLocationId;
	}

	public DbLocation patch(JSONObject json) {
		for (var field : json.keySet()){
			boolean known = true;
			switch (field) {
				case PARENT_LOCATION_ID:
					parentLocationId = json.getLong(field);
					break;
				case NAME:
					name = json.getString(field);
					break;
				case DESCRIPTION:
					description = json.getString(field);
					break;
				default:
					known = false;
			}
			if (known) dirtyFields.add(field);
		}
		return this;
	}

	@Override
	public DbLocation resolve() {
		return this;
	}

	@Override
	public Map<String, Object> toMap() {
		var map = super.toMap();
		if (description == null) description = "";
		map.put(OWNER,owner.toMap());
		map.put(NAME,name);
		map.put(DESCRIPTION,mapMarkdown(description));
		if (parentLocationId != null) map.put(PARENT_LOCATION_ID,parentLocationId);
		return map;
	}

	@Override
	public String toString() {
		return name;
	}
}
