package net.psammead.commonist.text;

import java.io.*;
import java.net.*;
import java.util.*;
import java.util.regex.*;

import net.psammead.commonist.data.*;
import net.psammead.util.*;

/**a set of licenses */
public class ParsedLicenses {
	private static final Logger log = new Logger(ParsedLicenses.class);
	
	private static final Pattern	LICENSE_DESCRIPTOR	= Pattern.compile("(\\{\\{[^\\}]+\\}\\})\\s*(.*)");

	public final List<LicenseData>	licenseDatas; 

	public ParsedLicenses(URL url) throws IOException {
		licenseDatas	= new ArrayList<LicenseData>();
		
		BufferedReader	in	 = null;
		try {
			in	= new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
			for (;;) {
				String	line	= in.readLine();
				if (line == null)	break;
				line	= line.trim();
				if (line.length() == 0)		continue;
				if (line.startsWith("#"))	continue;
				Matcher	matcher	= LICENSE_DESCRIPTOR.matcher(line);
				if (!matcher.matches())	{ log.warn("could not parse: " + line); continue; }
				LicenseData	data	= new LicenseData(
						matcher.group(1),
						matcher.group(2));
				licenseDatas.add(data);
			}
		}
		finally {
			if (in != null)
			try { in.close(); }
			catch (Exception e) { log.error("cannot close", e); }
		}
	}
}
