package tasks.mine.queries;

import java.util.Map;

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

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

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

public class ReleasesQuery {

	private final Writer writer;
	private final Reader reader;

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

	public boolean queryReleases() {

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

			String releasesUrl = urlMap.get(rowId);
			String all_releases_url = releasesUrl.substring(0, releasesUrl.indexOf("{"));
			all_releases_url = all_releases_url + "?per_page=100";

			ReleaseInfo releases = queryReleases(all_releases_url);
			if (releases != null) {
				writer.writeInfo(rowId, Config.XML_releases, releases.releasesCount);
				writer.writeInfo(rowId, Config.XML_releaseName, releases.name);
				writer.writeInfo(rowId, Config.XML_releaseDate, releases.date);
				writer.writeInfo(rowId, Config.XML_releaseUrl, releases.url);
				writer.writeInfo(rowId, Config.XML_releaseTar, releases.tarUrl);
				writer.writeInfo(rowId, Config.XML_releaseZip, releases.zipUrl);
			}
		}

		return true;
	}

	private ReleaseInfo queryReleases(String addr) {
		try {
			String result = Curl.getHTML(addr);
			System.out.println("Releases query finished " + addr);
			return parseReleasesQuery(result);
		} catch (Exception e) {
			return null;
		}
	}

	private ReleaseInfo parseReleasesQuery(String res) throws JSONException {

		ReleaseInfo releaseInfo = new ReleaseInfo();

		res = "{\"items\": " + res + "}";
		res = res.trim();
		JSONObject obj = new JSONObject(res);

		JSONArray arr = obj.getJSONArray("items");
		releaseInfo.releasesCount = arr.length();
		for (int i = 0; i < arr.length(); i++) {
			JSONObject item = arr.getJSONObject(i);

			releaseInfo.name = item.getString("name");
			releaseInfo.url = item.getString("html_url");
			releaseInfo.date = item.getString("published_at");

			if (item.has("tarball_url") || item.has("zipball_url")) {
				// If there is some source code
				if (item.has("tarball_url"))
					releaseInfo.tarUrl = item.getString("tarball_url");
				if (item.has("zipball_url"))
					releaseInfo.zipUrl = item.getString("zipball_url");
				break;
			}
		}
		return releaseInfo;
	}
}
