/*
 * Copyright 2006 Takahiro Nakamura.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */
package woolpack.convert;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import woolpack.fn.Fn;

/**
 * コンテキスト役をIPv4アドレスとしてネットワークアドレスを返す{@link Fn}です。
 * @author nakamura
 *
 * @param <E>
 */
public class NetMaskConverter<E extends Exception> implements Fn<String, String, E> {
	private static final int IP_COUNT = 4;
	private static final Pattern PATTERN = Pattern.compile("(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)");

	private String netMask;
	private int[] maskArray;

	public NetMaskConverter(final String netMask) {
		this.netMask = netMask;
		this.maskArray = toArray(netMask);
	}

	private static int[] toArray(final String s) {
		if (s == null) {
			return null;
		}
		final Matcher m = PATTERN.matcher(s);
		if (!m.matches()) {
			return null;
		}
		final int[] a = new int[IP_COUNT];
		for (int i = 0; i < a.length; i++) {
			a[i] = Integer.parseInt(m.group(i + 1));
		}
		return a;
	}

	public String exec(final String c) {
		final int[] a = toArray(c);
		if (a == null) {
			return null;
		}

		for (int i = 0; i < a.length; i++) {
			a[i] = a[i] & maskArray[i];
		}

		final StringBuilder sb = new StringBuilder();
		for (int i = 0; i < a.length; i++) {
			if (i != 0) {
				sb.append('.');
			}
			sb.append(a[i]);
		}

		return sb.toString();
	}

	public String getNetMask() {
		return netMask;
	}
	public void setNetMask(final String netMask) {
		this.netMask = netMask;
		this.maskArray = toArray(netMask);
	}
}
