package tasks.mine.queries;

import java.util.Map;

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

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

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

public class IssuesQuery {

	private final Writer writer;
	private final Reader reader;

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

	public boolean issuesQuery() {

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

			String issuesUrl = urlMap.get(rowId);
			String all_issues_url = issuesUrl.substring(0, issuesUrl.indexOf("{"));
			all_issues_url = all_issues_url + "?state=all&per_page=100";

			IssuesInfo issues = issuesQuery(all_issues_url);
			if (issues != null) {
				writer.writeInfo(rowId, Config.XML_firstIssues, issues.first_issues);
				writer.writeInfo(rowId, Config.XML_issuesRatio, issues.open_issues_ratio + "");
			}
		}

		return true;
	}

	private IssuesInfo issuesQuery(String addr) {
		try {
			String result = Curl.getHTML(addr);
			System.out.println("Issues query finished " + addr);
			return parseIssuesQuery(result);
		} catch (Exception e) {
			return null;
		}
	}

	private IssuesInfo parseIssuesQuery(String res) throws JSONException {
		IssuesInfo issuesInfo = new IssuesInfo();

		// Note: out of the first page (100) only
		res = "{\"items\": " + res + "}";
		res = res.trim();
		JSONObject obj = new JSONObject(res);

		double openIssues = 0;
		int issues = 0;
		JSONArray arr = obj.getJSONArray("items");
		for (int i = 0; i < arr.length(); i++) {
			JSONObject item = arr.getJSONObject(i);
			if (item.getString("state").equals("open"))
				openIssues++;
			issues++;
		}
		if (issues > 0) {
			issuesInfo.open_issues_ratio = openIssues * 100 / issues;
			issuesInfo.first_issues = issues;
		}
		return issuesInfo;
	}
}
