package com.pictc.utils;


import java.lang.reflect.Array;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;

@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class ArrayUtils {
	
	@SuppressWarnings("unchecked")
	public static <T> T[] of(T... parameters) {
		return parameters;
	}


	@SuppressWarnings("unchecked")
	public static <T>T[] valueOf(List<T> list){
		if(list!=null) {
			T[] result = null;
			for (int i = 0; i < list.size(); i++) {
				T item = list.get(i);
				if(result==null) {
					result = (T[]) Array.newInstance(item.getClass(),list.size());
				}
				result[i] = item;
			}
			return result;
		}
		return null;
	}
	
	
    @SuppressWarnings("unchecked")
	public static <T> T[] ofCollection(Collection<T> objs){
    	T[] result=null;
    	if(objs!=null) {
    		Iterator<T> it=objs.iterator();
    		int i=0;
        	while (it.hasNext()) {
        		T item =it.next();
				if(result==null) {
					result = (T[]) Array.newInstance(item.getClass(),objs.size());
				}
				result[i] = item;
        		i++;
    		}
    	}
    	return result;
    }
    
	public static <T> String join(T[] array){
		return join(array,",",null);
	}
	
	
	public static <T> String join(T[] array,String split){
		return join(array, split, null);
	}
	
	public static <T> String join(T[] array,String split,String suffix){
		if(array==null || array.length==0){
			return null;
		}
		StringBuilder str=new StringBuilder();
		for (int i = 0; i < array.length; i++) {
			if(i>0) {
				str.append(split);
			}
			if(suffix!=null) str.append(suffix);
			str.append(array[i].toString());
			if(suffix!=null) str.append(suffix);
		}
		return str.toString();
	}

}
