/* © 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.tools.Mappable;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;
import org.json.JSONObject;

public class Contact implements Mappable{
	private final static String X_CUSTOMER_NUMBER = "X-CUSTOMER-NUMBER";

	private long id;
	private String vcard;

	public Contact(long id, String vcard){
		this.id    = id;
		this.vcard = vcard;
	}

	public long id(){
		return id;
	}

	public static Contact of(ResultSet rs) throws SQLException {
		return new Contact(rs.getLong(ID),rs.getString(DATA));
	}

	public Contact patch(JSONObject json) {
		if (!(json.get(FROM) instanceof String from)) throw missingField(FROM);
		if (!(json.get(TO) instanceof String to)) throw missingField(TO);
		return new Contact(id,vcard.replace(from, to));
	}

	public Contact setCustomerNumber(String customerNumber) {
		if (vcard.contains(X_CUSTOMER_NUMBER)) {
			var pattern = format("^{0}:.*",X_CUSTOMER_NUMBER);
			var replacement = format("{0}:{1}",X_CUSTOMER_NUMBER,customerNumber);
			vcard = vcard.replaceAll(pattern,replacement);
		} else {
			var index = vcard.lastIndexOf("\n");
			vcard = format("{0}\r\n{1}:{2}{3}",vcard.substring(0,index),X_CUSTOMER_NUMBER,customerNumber,vcard.substring(index));
		}
		return this;
	}

	@Override
	public Map<String, Object> toMap() {
		return Map.of(ID,id,VCARD,vcard);
	}

	public String vcard(){
		return vcard;
	}
}
