/*
 * Copyright 2009-2013 Yuichiro Moriguchi
 *
 * 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 net.morilib.unix.glob;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;

import net.morilib.unix.charset.IntInterval;
import net.morilib.unix.charset.IntRange;
import net.morilib.unix.charset.UnixCharSetException;
import net.morilib.unix.charset.UnixCharSets;

/**
 * UNIX互換のワイルドカードを表現します。
 * 
 *
 * @author MORIGUCHI, Yuichiro 2011/04/24
 */
public final class Wildcard {

	//
	private static enum S1 { INIT, ESC1, SQUT, DQUT, ESC2 }

	//
	private IntRange[] chars;
	private List<Boolean> repeat;

	//
	private Wildcard(IntRange[] chars, List<Boolean> repeat) {
		this.chars   = chars;
		this.repeat  = repeat;
	}

	/**
	 * 与えられた文字列がワイルドカードにマッチするかを調べます。
	 * 
	 * @param cs 文字列
	 * @return マッチするときtrue
	 */
	public boolean matches(CharSequence cs) {
		Set<Integer> ss = new HashSet<Integer>();
		Set<Integer> ad = new HashSet<Integer>();

		ss.add(0);
		for(int p = 0; p < cs.length(); p++) {
			Iterator<Integer> i = ss.iterator();
			int c = cs.charAt(p);

			while(i.hasNext()) {
				int s = i.next();

				if(chars[s].contains(c)) {
					ad.add(s + 1);
				}
				if(!repeat.get(s)) {
					i.remove();
				}
			}
			ss.addAll(ad);
			ad.clear();
			if(ss.isEmpty())  break;
		}
		return (ss.contains(chars.length - 1));
	}

	/**
	 * 
	 * @param cs
	 * @param start
	 * @return
	 */
	public int lookingAtLongest(CharSequence cs, int start) {
		SortedSet<Integer> ss = new TreeSet<Integer>();
		SortedSet<Integer> ad = new TreeSet<Integer>();
		Iterator<Integer> i;
		int c, s, r;

		ss.add(0);
		r = ss.contains(chars.length - 1) ? start : -1;
		for(int p = start; p < cs.length(); p++) {
			i = ss.iterator();
			c = cs.charAt(p);
			while(i.hasNext()) {
				s = i.next();
				if(chars[s].contains(c))  ad.add(s + 1);
				if(!repeat.get(s))  i.remove();
			}
			ss.addAll(ad);
			ad.clear();
			if(ss.isEmpty())  break;
			if(ss.contains(chars.length - 1))  r = p + 1;
		}
		return r;
	}

	/**
	 * 
	 * @param cs
	 * @param start
	 * @return
	 */
	public int lookingAtShortest(CharSequence cs, int start) {
		SortedSet<Integer> ss = new TreeSet<Integer>();
		SortedSet<Integer> ad = new TreeSet<Integer>();
		Iterator<Integer> i;
		int c, s;

		ss.add(0);
		for(int p = start; p < cs.length(); p++) {
			i = ss.iterator();
			c = cs.charAt(p);
			while(i.hasNext()) {
				s = i.next();
				if(chars[s].contains(c))  ad.add(s + 1);
				if(!repeat.get(s))  i.remove();
			}
			ss.addAll(ad);
			ad.clear();
			if(ss.isEmpty())  break;
			if(ss.contains(chars.length - 1))  return p + 1;
		}
		return -1;
	}

	int[] _findLongest(CharSequence cs, int s, int[] r) {
		int k, l;

		for(k = s; k <= cs.length(); k++) {
			if((l = lookingAtLongest(cs, k)) >= 0) {
				r[0] = k;  r[1] = l;
				return r;
			}
		}
		return null;
	}

	int[] _findShortest(CharSequence cs, int s, int[] r) {
		int k, l;

		for(k = s; k <= cs.length(); k++) {
			if((l = lookingAtShortest(cs, k)) >= 0) {
				r[0] = k;  r[1] = l;
				return r;
			}
		}
		return null;
	}

	/**
	 * 
	 * @param cs
	 * @return
	 */
	public int lastLookingAtLongest(CharSequence s) {
		int[] a = new int[2];

		if(_findLongest(s, 0, a) != null && a[1] == s.length()) {
			return a[0];
		}
		return -1;
	}

	/**
	 * 
	 * @param s
	 * @return
	 */
	public int lastLookingAtShortest(CharSequence s) {
		int[] a = new int[2];

		for(int i = s.length(); i >= 0; i--) {
			if(_findLongest(s, i, a) != null && a[1] == s.length()) {
				return i;
			}
		}
		return -1;
	}

	/**
	 * ワイルドカードをコンパイルします。
	 * 
	 * @param pt ワイルドカードの表現
	 * @return ワイルドカード
	 * @throws WildcardSyntaxException 
	 */
	public static Wildcard compile(CharSequence pt) {
		List<IntRange> rl = new ArrayList<IntRange>();
		List<Boolean>  rp = new ArrayList<Boolean>();
		S1 stat = S1.INIT;
		boolean b = true;
		int c, p = 0, z;

		for(; p < pt.length(); p++) {
			c = pt.charAt(p);
			switch(stat) {
			case INIT:
				switch(c) {
				case '*':
					if(b)  rp.add(true);
					b = false;
					break;
				case '?':
					rl.add(UnixCharSets.ALL_CHAR);
					if(b)  rp.add(false);
					b = true;
					break;
				case '[':
					for(z = p + 1; true; z++) {
						if(z >= pt.length()) {
							throw new WildcardSyntaxException();
						} else if(pt.charAt(z) == ']') {
							break;
						}
					}

					try {
						rl.add(UnixCharSets.parse(
								pt.subSequence(p + 1, z)));
					} catch(UnixCharSetException e) {
						throw new WildcardSyntaxException(e);
					}
					if(b)  rp.add(false);
					b = true;
					p = z;
					break;
				case '\'':
					stat = S1.SQUT;
					break;
				case '\"':
					stat = S1.DQUT;
					break;
				case '\\':
					stat = S1.ESC1;
					break;
				default:
					rl.add(new IntInterval((char)c));
					if(b)  rp.add(false);
					b = true;
					break;
				}
				break;
			case ESC1:
				stat = S1.INIT;
				rl.add(new IntInterval((char)c));
				if(b)  rp.add(false);
				b = true;
				break;
			case SQUT:
				if(c == '\'') {
					stat = S1.INIT;
				} else {
					rl.add(new IntInterval((char)c));
					if(b)  rp.add(false);
					b = true;
				}
				break;
			case DQUT:
				if(c == '\"') {
					stat = S1.INIT;
				} else if(c == '\\') {
					stat = S1.ESC2;
				} else {
					rl.add(new IntInterval((char)c));
					if(b)  rp.add(false);
					b = true;
				}
				break;
			case ESC2:
				stat = S1.DQUT;
				rl.add(new IntInterval((char)c));
				if(b)  rp.add(false);
				b = true;
				break;
			}
		}

		if(b)  rp.add(false);
		rl.add(IntRange.O);
		return new Wildcard(rl.toArray(new IntRange[0]), rp);
	}

	/**
	 * ワイルドカードが与えられた文字列にマッチするかを調べます。
	 * 
	 * @param pt ワイルドカード
	 * @param cs 文字列
	 * @return マッチするときtrue
	 */
	public static boolean matches(CharSequence pt, CharSequence cs) {
		return compile(pt).matches(cs);
	}

}
