/*
 * Copyright (c) 2004-2017, by Alex Leigh.
 * All rights reserved.
 *
 * THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE
 * The copyright notice above does not evidence any
 * actual or intended publication of such source code.
 */

package lc.mecha.util;

import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Set;
import java.util.Stack;

/**
 * A stack that accumulates parts of a string separated by a given delimiter
 * (such as paths, URLs, package names, etc).
 *
 * @author Alex Leigh
 */
public final class StringAccumulatorV2 extends Stack<String> {
    private final String delim;
    private final boolean leading;

    public StringAccumulatorV2(final String delim) {
        this(delim, false);
    }

    public StringAccumulatorV2(final String delim, final boolean leading) {
        this.delim = delim;
        this.leading = leading;
    }

    public boolean pushUnique(final String str) {
        for(String s : this) {
            if(StringUtil.safeEquals(str, s)) return false;
        }

        push(str);
        return true;
    }

    public void push(List l) {
        for (Object o : l) {
            push(o.toString());
        }
    }

    public void push(final String... str) {
        for (final String s : str) {
            push(s);
        }
    }

    public void push(Set s) {
        for (Object o : s) {
            push(o.toString());
        }
    }

    public String quickString(final String value) {
        push(value);
        final String s = asString();
        pop();
        return s;
    }

    /**
     * Return the string representation of the current state of the accumulator. This method replaces the prior
     * <code>toString()</code> implementation which should no longer be relied on to generate the user string.
     *
     * @since mk11 (ZERO CONTRAST)
     */
    public String asString() {
        final StringBuilder sb = new StringBuilder();
        for (final String s : this) {
            if (sb.length() != 0 || leading)
                sb.append(delim);
            sb.append(s);
        }
        return sb.toString();
    }

    public String getDelim() {
        return delim;
    }

    public boolean isLeading() {
        return leading;
    }

    public void writeLine(OutputStream os) throws IOException {
        String abc = asString() + "\n";
        os.write(abc.getBytes(StandardCharsets.UTF_8));
    }
}
