package at.procon.dip.ingestion.mail;

import at.procon.dip.ingestion.config.DipIngestionProperties;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

@Component
public class CamelMailServerEndpointUriFactory implements MailServerEndpointUriFactory {

    @Override
    public String buildConsumerUri(DipIngestionProperties.MailRouteProperties properties) {
        if (properties == null) {
            throw new IllegalArgumentException("Mail route properties must not be null");
        }
        if (!StringUtils.hasText(properties.getHost())) {
            throw new IllegalArgumentException("dip.ingestion.mail-route.host must not be blank when the mail route is enabled");
        }
        if (!StringUtils.hasText(properties.getUsername())) {
            throw new IllegalArgumentException("dip.ingestion.mail-route.username must not be blank when the mail route is enabled");
        }
        if (properties.getProtocol() == null) {
            throw new IllegalArgumentException("dip.ingestion.mail-route.protocol must not be null");
        }

        StringBuilder uri = new StringBuilder();
        uri.append(properties.getProtocol().camelScheme()).append("://");
        uri.append(properties.getHost());
        if (properties.getPort() != null) {
            uri.append(":").append(properties.getPort());
        }
        uri.append("?username=").append(encode(properties.getUsername()));
        uri.append("&password=").append(encode(properties.getPassword()));
        uri.append("&folderName=").append(encode(defaultIfBlank(properties.getFolderName(), "INBOX")));
        uri.append("&delete=").append(properties.isDelete());
        uri.append("&peek=").append(properties.isPeek());
        uri.append("&unseen=").append(properties.isUnseen());
        uri.append("&delay=").append(properties.getDelay());
        uri.append("&maxMessagesPerPoll=").append(properties.getMaxMessagesPerPoll());
        uri.append("&fetchSize=").append(properties.getFetchSize());
        uri.append("&closeFolder=").append(properties.isCloseFolder());
        uri.append("&debugMode=").append(properties.isDebugMode());
        uri.append("&connectionTimeout=").append(properties.getConnectionTimeout());
        return uri.toString();
    }

    private String encode(String value) {
        if (value == null) {
            return "";
        }
        return URLEncoder.encode(value, StandardCharsets.UTF_8);
    }

    private String defaultIfBlank(String value, String defaultValue) {
        return StringUtils.hasText(value) ? value : defaultValue;
    }
}
