package tasks.mine.queries;

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

import data.Repository;
import io.Writer;
import tasks.util.Curl;

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

public class SearchQuery {

	private final Writer writer;

	public SearchQuery(Writer writer) {
		this.writer = writer;
	}

	public boolean searchRepos(String addr) {
		try {
			String result = Curl.getHTML(addr);
			System.out.println("Main search query terminated " + addr);
			parseSearchQuery(result);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	private void parseSearchQuery(String res) throws JSONException {
		JSONObject obj = new JSONObject(res.trim());
		JSONArray arr = obj.getJSONArray("items");
		for (int i = 0; i < arr.length(); i++) {
			JSONObject item = arr.getJSONObject(i);
			Repository repo = new Repository(item);
			writer.writeSearchInfo(repo);
		}
	}
}
