
// GetHeadlines.java
// Ahmed Bouchefra, March 2020
// Modified by Andrew Davison, ad@coe.psu.ac.th, July 2023

/* Get the headlines for a specified country. If a number
   is included then that article's URL is loaded into
   a browser.

  Usage:
    > compile GetHeadlines.java
    > run GetHeadlines <2-letter country> [<story num>]
  e.g. 
    > run GetHeadlines gb
    > run GetHeadlines gb 5

  More info: https://newsapi.org/docs/endpoints/top-headlines
*/



import java.util.*;


public class GetHeadlines
{

  public static void main(String[] args)
  {
    String country = "us";
    int newsItem = -1;

    if ((args.length == 0) || (args.length > 2)) {
      System.out.println("Usage: run GetHeadlines <2-letter country> [<story num>]");
      NewsUtils.listCountries();
      return;
    }

    if (NewsUtils.isCountry(args[0]))
      country = args[0];
    else {
      System.out.println("Not a known country code; using \"" +
                     country + "\"");
    }

    if (args.length == 2)
      newsItem = NewsUtils.getInt(args[1]);

    String request = "https://newsapi.org/v2/top-headlines?" +
                          "country=" + country;
    News news = NewsUtils.getNews(request);
    if (news != null) {
      if (newsItem != -1)
        NewsUtils.showArticle(news, newsItem);
      else
        NewsUtils.listNews(news);
    }
  } /* main */

}  // end of GetHeadlines class

