package de.assecutor.votianlt.pages.base.ui.component;

import de.assecutor.votianlt.model.Customer;
import java.util.Map;

public final class CustomerAddressLabelHelper {

    private CustomerAddressLabelHelper() {
    }

    /** Adds the customer under its full address label ("Name, Street No, Zip City"). */
    public static void put(Map<String, Customer> target, Customer customer, String fallbackLabel) {
        target.put(build(customer, fallbackLabel), customer);
    }

    /** Adds the customer under its plain name label (company or person name). */
    public static void putName(Map<String, Customer> target, Customer customer, String fallbackLabel) {
        target.put(buildName(customer, fallbackLabel), customer);
    }

    /**
     * Builds the selection label as full address ("Name, Street No, Zip City")
     * so that entries with the same name (e.g. branches of one company) remain
     * distinguishable in the combo boxes.
     */
    public static String build(Customer customer, String fallbackLabel) {
        if (customer == null) {
            return fallbackLabel;
        }

        StringBuilder label = new StringBuilder(buildName(customer, fallbackLabel));
        String street = trimToNull(join(" ", customer.getStreet(), customer.getHouseNumber()));
        if (street != null) {
            label.append(", ").append(street);
        }
        String city = trimToNull(join(" ", customer.getZip(), customer.getCity()));
        if (city != null) {
            label.append(", ").append(city);
        }
        return label.toString();
    }

    /** Plain name label: company name, otherwise person name, otherwise fallback. */
    public static String buildName(Customer customer, String fallbackLabel) {
        if (customer == null) {
            return fallbackLabel;
        }

        String name = trimToNull(customer.getCompanyName());
        if (name == null) {
            name = trimToNull(join(" ", customer.getFirstname(), customer.getLastName()));
        }
        return name != null ? name : fallbackLabel;
    }

    public static String resolveCompanyValue(Map<String, Customer> addressOptions, String comboValue) {
        if (addressOptions.containsKey(comboValue)) {
            Customer customer = addressOptions.get(comboValue);
            return customer != null ? customer.getCompanyName() : null;
        }
        return comboValue;
    }

    private static String join(String separator, String first, String second) {
        String left = first != null ? first.trim() : "";
        String right = second != null ? second.trim() : "";
        return (left + separator + right).trim();
    }

    private static String trimToNull(String value) {
        if (value == null) {
            return null;
        }
        String trimmed = value.trim();
        return trimmed.isEmpty() ? null : trimmed;
    }
}
