package cn.axzo.msg.center.service.util;

import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;

import static java.util.stream.Collectors.joining;

/**
 * @author yanglin
 */
@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
public class IdBuilder {

    private final List<Object> buf = new ArrayList<>();
    private final boolean appendAbsentValue;

    public static IdBuilder builder() {
        return new IdBuilder(false);
    }

    public static IdBuilder builder(boolean appendAbsentValue) {
        return new IdBuilder(appendAbsentValue);
    }

    public IdBuilder append(Object value) {
        if (isAbsentValue(value) && !appendAbsentValue)
            return this;
        buf.add(value);
        return this;
    }

    private static boolean isAbsentValue(Object value) {
        if (value == null)
            return true;
        if (value instanceof String)
            return StringUtils.isBlank((String) value);
        return false;
    }

    public String build() {
        return buf.stream().map(String::valueOf).collect(joining(":"));
    }

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