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 commit information, parses the answer and writes
 * it to the xml database
 * 
 * @author Lisa Nguyen Quang Do
 */

public class CommitsQuery {

	private final Writer writer;
	private final Reader reader;

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

	public boolean queryCommits() {
		Map<Integer, String> urlMap = reader.getUrls(Config.XML_commitsUrl, false);
		for (Integer rowId : urlMap.keySet()) {
			String commitsUrl = urlMap.get(rowId);
			String commits_year_url = commitsUrl.substring(0, commitsUrl.indexOf("/commits"));
			commits_year_url = commits_year_url + "/stats/commit_activity";
			int commitsLastYear = queryCommits(commits_year_url);

			String shaUrl = urlMap.get(rowId);
			shaUrl = commitsUrl.substring(0, shaUrl.indexOf("{"));
			String latestCommitSha = queryLatestCommit(shaUrl);

			writer.writeInfo(rowId, Config.XML_commitsLastYear, commitsLastYear);
			writer.writeInfo(rowId, Config.XML_sha, latestCommitSha);
		}

		return true;
	}

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

	private int parseCommitsQuery(String res) throws JSONException {
		int commitsLastYear = -1;
		res = "{\"items\": " + res + "}";
		res = res.trim();
		JSONObject obj = new JSONObject(res);
		if (obj.get("items") instanceof JSONArray) {
			JSONArray arr = obj.getJSONArray("items");
			for (int i = 0; i < arr.length(); i++) {
				JSONObject item = arr.getJSONObject(i);
				int count = item.getInt("total");
				if (commitsLastYear == -1)
					commitsLastYear = count;
				else
					commitsLastYear += count;
			}
		}
		return commitsLastYear;
	}

	private String queryLatestCommit(String addr) {
		try {
			String result = Curl.getHTML(addr);
			System.out.println("Latest commit query finished " + addr);
			return parseCommitQuery(result);
		} catch (Exception e) {
			return "";
		}
	}

	private String parseCommitQuery(String res) throws JSONException {
		res = "{\"items\": " + res + "}";
		res = res.trim();
		JSONObject obj = new JSONObject(res);
		if (obj.get("items") instanceof JSONArray) {
			JSONArray arr = obj.getJSONArray("items");
			if (arr.length() > 0) {
				JSONObject item = arr.getJSONObject(0);
				String sha = item.getString("sha");
				return sha;
			}
		}
		return "";
	}
}
