package tag.matcherImplementations;

import datastructures.json.JSONParser;
import link.LinkUrl;
import tag.OptionalTag;
import tag.Tag;
import tag.TagMatcher;
import tag.TagName;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.Map;
import java.util.Scanner;

import static java.nio.charset.StandardCharsets.UTF_8;

public class GitHubTagMatcher extends TagMatcher {

	public GitHubTagMatcher() {
		tagName = new TagName("github");
	}

	public TagName getName() {
		return tagName;
	}

	public String getAdditionInfo(String urlPath) {

		try {
			URL url = new URL("https://api.github.com/repos" + urlPath);
			HttpURLConnection con = (HttpURLConnection) url.openConnection();
			con.setRequestMethod("GET");

			con.setRequestProperty("accept", "application/vnd.github.v3+json");

			// This line makes the request
			InputStream responseStream = con.getInputStream();

			String text = new String(responseStream.readAllBytes(), UTF_8);

			var parsedJSON = (Map<?, ?>) JSONParser.parseJSON(text);

			return (String) parsedJSON.get("description");

		}
		catch (JSONParser.JSONParseException e) {
			e.printStackTrace();
		}
		catch (ProtocolException e) {
			return "";
		}
		catch (MalformedURLException e) {
			return "";
		}
		catch (IOException e) {
			return "";
		}
		catch (ClassCastException e) {
			return "";
		}
		return "";
	}

	@Override
	public OptionalTag ifMatches(LinkUrl linkUrl) {
		if (linkUrl.getUrl().getHost().equals("github.com")) {

			String additionInfo = getAdditionInfo(linkUrl.getUrl().getPath());
			return OptionalTag.of(new Tag(getName()).addAdditionalData(additionInfo));
		}
		return OptionalTag.empty();
	}
}
