
// GetSources.java
// Andrew Davison, ad@coe.psu.ac.th, July 2023

/* Obtain the news sources for top-headlines for
   a given country. The code lists the sources' 
   ID (which is used in other queries) and the name.

  Usage:
    > compile GetSources.java
    > run GetSources <2-letter country>
  e.g. 
    > run GetSources gb

  More info: https://newsapi.org/docs/endpoints/sources
*/


import java.util.*;
import com.google.gson.Gson;


public class GetSources
{

  public static void main(String[] args) // throws Exception
  {
    String country = "us";
    if (args.length != 1) {
      System.out.println("Usage: run GetSources <2-letter country>");
      NewsUtils.listCountries();
      return;
    }

    if (NewsUtils.isCountry(args[0]))
      country = args[0];
    else {
      System.out.println("Not a known country code; using \"" +
                     country + "\"");
    }

    String request =
         "https://newsapi.org/v2/top-headlines/sources?" +
                "country=" + country;
    String response = NewsUtils.getNewsResponse(request);

    NewsSources ns = new Gson().fromJson(response, 
                                             NewsSources.class);
    if (ns.status.equals("error")) {
      NewsError err = new Gson().fromJson(response, NewsError.class);
      System.out.println("Error: " + err.message);
      return;
    }

    int numSources = ns.sources.size();
    System.out.println("Found " + numSources + " sources:");
    for (int i = 0 ; i < numSources; i++) {
      NewsSource source = ns.sources.get(i);
      System.out.println((i+1) + ". " + source.id + ", \"" + 
                                        source.name + "\"");
    }
  } /* main */

}  // end of GetSources class

