package tasks.mine.queries;

import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import io.Reader;
import io.Writer;
import main.Config;
import tasks.util.Curl;

/**
 * Queries the GitHub API for contributors information, parses the answer and
 * writes it to the xml database
 * 
 * @author Lisa Nguyen Quang Do
 */

public class ContributorsQuery {

	private final Writer writer;
	private final Reader reader;

	public ContributorsQuery(Writer writer, Reader reader) {
		this.writer = writer;
		this.reader = reader;
	}

	public boolean contributorsQuery() {

		Map<Integer, String> urlMap = reader.getUrls(Config.XML_contributorsUrl, true);
		for (Integer rowId : urlMap.keySet()) {

			String contributorsUrl = urlMap.get(rowId);

			int contributors = contributorsQuery(contributorsUrl);
			if (contributors < 0)
				contributors = contributorsQuery(contributorsUrl);

			if (contributors >= 0)
				writer.writeInfo(rowId, Config.XML_contributors, contributors);
		}

		return true;
	}

	private int contributorsQuery(String addr) {
		try {
			String result = Curl.getHTML(addr);
			System.out.println("Contributors query finished " + addr);
			return parseContributorsQuery(result);
		} catch (Exception e) {
			return -1;
		}
	}

	private int parseContributorsQuery(String res) throws JSONException {
		res = "{\"items\": " + res + "}";
		res = res.trim();
		JSONObject obj = new JSONObject(res);
		JSONArray arr = obj.getJSONArray("items");
		return arr.length();
	}
}
