package finanny;

import java.net.*;
import java.io.*;
import java.util.ArrayList;
import java.util.StringTokenizer;

//Declaration of our stockQuote class. This class operates at the network level.
public class StockQuote {

    // Take the symbol and tags and send a request over the network
    String printStockQuote(String symbol, ArrayList<String> tagNames, String functionString) {
        // Our network variables
        URL url;
        URLConnection urlConn;
        // Store our input in an InputStreamReader
        InputStreamReader inStream = null;
        // Buffer the data for faster data transfer
        BufferedReader buff = null;

        try {
            url = new // Open the network connection with the proper symbol and tags
            URL("https://www.alphavantage.co/query?function=" + functionString + "&symbol=" + symbol
                    + "&apikey=6DLLEA7TKPPUYT2G");
            urlConn = url.openConnection();
            // Display this in our console so we see what string we have built
            System.out.println("URL: https://www.alphavantage.co/query?function=" + functionString + "&symbol=" + symbol
                    + "&apikey=6DLLEA7TKPPUYT2G");
            // Read the stream from the network connection
            inStream = new InputStreamReader(urlConn.getInputStream());
            buff = new BufferedReader(inStream);

            // Read the stream line by line and store in a StringBuilder
            StringBuilder responseBuilder = new StringBuilder();
            String line;
            while ((line = buff.readLine()) != null) {
                responseBuilder.append(line);
            }

            // Close the BufferedReader
            buff.close();

            // Convert the StringBuilder content to a string
            String jsonResponse = responseBuilder.toString();
            String formattedJson = jsonResponse.replace(",", ",\n");

            // Print the JSON response
            System.out.println("JSON Response:");
            System.out.println(formattedJson);

            return formattedJson;

        } catch (MalformedURLException e) {// Some error handling of bad network connections
            System.out.println("Please check the spelling of "
                    + "the URL: " + e.toString());
            return "";
        } catch (IOException e1) {// Some error handling of bad network connections
            System.out.println("Can't read from the Internet: " +
                    e1.toString());
            return "";
        } finally {
            try {
                inStream.close();// Close your streams
                buff.close();
            } catch (Exception e) {
                System.out.println("StockQuote: can't close streams" + e.getMessage());
            }
        }
    }
}
