package com.walmartlabs.concord.common;

/*-
 * *****
 * Concord
 * -----
 * Copyright (C) 2017 - 2021 Walmart Inc.
 * -----
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =====
 */

import java.util.Collection;

public class ToStringHelper {

    public static ToStringHelper prefix(String prefix) {
        return new ToStringHelper(prefix);
    }

    private final String prefix;
    private final StringBuilder builder = new StringBuilder();
    private boolean appendSeparator = false;

    public ToStringHelper(String prefix) {
        this.prefix = prefix;
    }

    public ToStringHelper add(String name, Object value) {
        return addNameValue(name, value);
    }

    public ToStringHelper add(String name, Number value) {
        return addNameValue(name, value);
    }

    public ToStringHelper add(String name, String value) {
        if (value == null) {
            return this;
        }

        return addNameValue(name, "\"" + value + "\"");
    }

    public ToStringHelper add(String name, Collection<?> value) {
        if (value == null || value.isEmpty()) {
            return this;
        }

        return addNameValue(name, value);
    }

    public String toString() {
        builder.insert(0, '{');
        if (prefix != null) {
            builder.insert(0, prefix);
        }
        builder.append('}');
        return builder.toString();
    }

    private ToStringHelper addNameValue(String name, Object value) {
        if (value == null) {
            return this;
        }

        if (appendSeparator) {
            builder.append(", ");
        }
        builder.append(name).append('=').append(value);

        appendSeparator = true;

        return this;
    }
}
