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

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

import de.srsoftware.umbrella.core.exceptions.UmbrellaException;
import org.json.JSONObject;

public class User {
	private final String lang;
    private final String name;
	private final EmailAddress email;

	public User(String name, EmailAddress email, String languageCode){
		lang = languageCode;
		this.name = name;
		this.email = email;
	}

	public EmailAddress email(){
		return email;
	}

	@Override
	public boolean equals(Object o) {
		if (!(o instanceof User user)) return false;
		return email.equals(user.email);
	}

	@Override
	public int hashCode() {
		return email.hashCode();
	}

	public String language(){
		return lang;
	}

	public String name(){
		return name;
	}

	public static User of(JSONObject json) throws UmbrellaException {
		if (json.has(USER)) json = json.getJSONObject(USER);

		if (!(json.has(NAME) && json.get(NAME) instanceof String name)) throw missingField(NAME);
		if (!(json.has(EMAIL) && json.get(EMAIL) instanceof String email)) throw missingField(EMAIL);
		if (!(json.has(LANGUAGE) && json.get(LANGUAGE) instanceof String lang)) throw missingField(LANGUAGE);

		var addr = new EmailAddress(email);
		if (json.has(ID) && json.get(ID) instanceof Number id) {
			var theme = json.has(THEME) ? json.getString(THEME) : null;
			return new UmbrellaUser(id.longValue(), name, addr, theme, lang);
		}
		return new User(name,addr,lang);
	}

	@Override
	public String toString() {
		return email == null ? name : format("{0} ({1})",name,email);
	}
}
