package com.nifty.cloud.ncs.services.validator;

import java.util.ArrayList;
import java.util.List;

import com.nifty.cloud.ncs.NiftyCloudClientException;

/**
 * バケット名の妥当性をチェックします。
 *
 */
public class BucketNameValidator
{
	private static final String IP_REGEX = "^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$";
	private static final String BUCKET_REGEX = "^[0-9a-zA-Z][0-9a-zA-Z\\.\\-_]*$";

	/**
	 * bucket名の妥当性確認を行います。
	 * bucket名が不正な場合、不正理由を示すエラーメッセージのリストを返却します。
	 *
	 * @param value
	 * 			bucket名
	 * @return エラー理由を示すエラーメッセージのリスト
	 */
	public static List<ValidationMessage> validate(String value) throws NiftyCloudClientException
	{
		// execute validation.
		List<ValidationMessage> list = new ArrayList<ValidationMessage>();

		if (value == null) {
			addMessage(list, "Bucket name can not be null.", value);
			return (list);
		}

		String bucketName = value.trim();

		if (bucketName.toLowerCase().equals(bucketName) == false) {
			addMessage(list, "Bucket name must not be contain uppercase characters.", value);
		}

		if (bucketName.contains("_")) {
			addMessage(list, "Bucket name must not be contain '_'.", value);
		}

		if (bucketName.length() < 3 || bucketName.length() > 63) {
			addMessage(list, "Bucket name must be between 3 and 63 characters long.", value);
		}

		if (bucketName.endsWith("-")) {
			addMessage(list, "Bucket name must not end with '-'.", value);
		}

		if (bucketName.endsWith(".")) {
			addMessage(list, "Bucket name must not end with '.'.", value);
		}

		if (bucketName.contains("..")) {
			addMessage(list, "Bucket name must not contain two repeated dots.", value);
		}

		if (bucketName.contains(".-") || bucketName.contains("-.")) {
			addMessage(list, "Bucket name must not contain periods next to dashed.", value);
		}

		if (bucketName.matches(IP_REGEX)) {
			addMessage(list, "Bucket name must not be formatted as an IP address.", value);
		}

		if (bucketName.matches(BUCKET_REGEX) == false) {
			addMessage(list, "Bucket name can contain lowercase letters, numbers, periods (.), and dashes (-).", value);
		}

		return (list);
	}

	/**
	 *
	 * @param list
	 * @param message
	 * @param path
	 * @param value
	 */
	private static void addMessage(List<ValidationMessage> list, String message, Object value)
	{
		ValidationMessage validationMessage = new ValidationMessage(message, value);
		list.add(validationMessage);
	}

}
