package com.bocloud.ims.service.utils;

import java.util.List;
import java.util.Objects;

import com.google.common.collect.Lists;

public class ListUtils {

	public static List<String> getList(String value) {
		List<String> list = Lists.newArrayList();
		list.add(value);
		return list;
	}

	public static List<String> addValue(List<String> list, String value) {
		if (null == list) {
			list = Lists.newArrayList();
		}
		list.add(value);
		return list;
	}

	/**
	 * 获取子列表subList在列表list中第一个元素出现的下标
	 * <p>
	 * 如果subList不是list的值列表，返回-1
	 * </p>
	 *
	 * @param list
	 *            列表
	 * @param subList
	 *            子列表
	 * @param <T>
	 *            列表元素的类型
	 * @return 子列表subList在列表list中第一个元素出现的下标
	 */
	public static <T> int indexOf(List<T> list, List<T> subList) {
		Objects.requireNonNull(list, "list");
		Objects.requireNonNull(subList, "subList");

		int size = list.size();
		int subSize = subList.size();

		if (subSize == 0) {
			throw new IllegalArgumentException("子列表的元素个数不能为0");
		}

		if (size < subSize) {
			return -1;
		}

		int j;
		boolean find;
		T first = subList.get(0);
		T e;

		int remainSize = size;

		for (int i = 0; i < size; i++) {
			if (remainSize-- < subSize) {
				break;
			}

			e = list.get(i);
			if (objectEquals(first, e)) {
				find = true;

				for (j = 1; j < subSize; j++) {
					if (!objectEquals(subList.get(j), list.get(i + j))) {
						find = false;
						break;
					}
				}

				if (find) {
					return i;
				}
			}
		}

		return -1;
	}

	private static <T> boolean objectEquals(T t1, T t2) {
		return (t1 == t2) || (t1 != null && t2 != null && t1.equals(t2));
	}
}
