/*
 * (c) Copyright Sysdeo SA 2001, 2002.
 * All Rights Reserved.
 */

package com.sysdeo.eclipse.tomcat;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.StringTokenizer;

/**
 * StringUtil
 *
 */
public final class StringUtil {

	/**
	 * Constructor
	 */
	private StringUtil() {
		throw new AssertionError();
	}

	/**
	 * Concat two arrays of Strings,
	 * part2 is appended to part1
	 * @param part1 String[]
	 * @param part2 String[]
	 * @return String[]
	 */
	public static String[] concat(final String[] part1, final String[] part2) {
		String[] full = new String[part1.length + part2.length];
		System.arraycopy(part1, 0, full, 0, part1.length);
		System.arraycopy(part2, 0, full, part1.length, part2.length);
		return full;
	}

	/**
	 * Concat two arrays of Strings, and prevent that duplicate
	 * Strings are present in result
	 * part2 is appended to part1
	 * @param part1 String[]
	 * @param part2 String[]
	 * @return String[]
	 */
	public static String[] concatUniq(final String[] part1, final String[] part2) {
		ArrayList<String> nlist = new ArrayList<>();

		for (final String part : part1) {
			if (!nlist.contains(part)) {
				nlist.add(part);
			}
		}

		for (final String part : part2) {
			if (!nlist.contains(part)) {
				nlist.add(part);
			}
		}

		return nlist.toArray(new String[nlist.size()]);
	}

	/**
	 * See StringTokenizer for delim parameter format
	 * @param str String
	 * @param delim String
	 * @return String[]
	 */
	public static String[] cutString(final String str, final String delim) {
		ArrayList<String> strings = new ArrayList<>();
		StringTokenizer tokenizer = new StringTokenizer(str, delim);
		while (tokenizer.hasMoreTokens()) {
			try {
				strings.add(URLDecoder.decode(tokenizer.nextToken(), "UTF-8"));
			} catch (final UnsupportedEncodingException ex) {
				throw new RuntimeException(ex);
			}
		}

		return strings.toArray(new String[strings.size()]);
	}
}
