// Copyright (c) Trend Micro Inc. 2004-2012, All Rights Reserved

package com.trendmicro.webserviceclient.utils;

import java.util.Calendar;
import java.util.GregorianCalendar;

import com.trendmicro.webserviceclient.generated.Manager;
import com.trendmicro.webserviceclient.generated.ManagerService;
import com.trendmicro.webserviceclient.generated.ManagerServiceLocator;

/**
 * ClientUtils: This class is designed to keep basic info and common utility functions
 * used by the Deep Security WebService client sample applications.
 */
public class ClientUtils {
	public ManagerService _Service = new ManagerServiceLocator();
	public Manager _ManagerService = null;

	public static int DEF_ARGS = 3;
	public static String DEF_USAGE = " <webservice url> <username> <password>";

	public static String _application_name;
	public static int _arg_size;
	public static String _arg_usage;
	public static String[] _args;

	public ClientUtils(String app_name, int arg_count, String usage, String[] args) throws Exception {
		_application_name = app_name;
		if(_arg_size >= 0)
			_arg_size = arg_count;
		else
			_arg_size = DEF_ARGS;
		if((usage != null) && (usage.length() > 0))
			_arg_usage = usage;
		else
			_arg_usage = DEF_USAGE;
		_args = args;
	}

	public boolean validateArgs() {
		if(_args == null)
			// Arguments are not set.
			return false;
		if(_args.length != _arg_size)
			// Incorrect number of arguments.
			return false;
		return true;
	}

	public String getArg(int position) throws Exception {
		if((position < 0) || (position >= _args.length))
			throw new Exception("Requested argument does not exist.");
		return _args[position];
	}

	public String[] getArgs() {
		return _args;
	}

	public void printUsage() {
		printUsage("");
	}

	public void printUsage(String message) {
		if((message != null) || (message.length() > 0))
			log(message);
		log(_application_name + " " + _arg_usage);
	}

	public void log(String output) {
		System.out.println(output);
	}

	public Calendar getRangeDate() {
		return getRangeDate(0);
	}

	public Calendar getRangeDate(int hours) {
		Calendar range = new GregorianCalendar();
		range.add(Calendar.HOUR, hours);
		return range;
	}

	public boolean testForId(String identifier) {
		try {
			Integer.parseInt(identifier);
			return true;
		} catch(NumberFormatException ne) {
			return false;
		}
	}

	public int[] add(int[] array, int value) {
		int[] newArray = new int[array.length + 1];
		System.arraycopy(array, 0, newArray, 0, array.length);
		newArray[newArray.length - 1] = value;
		return newArray;
	}
}