package org.academiadecodigo.enuminatti.jurl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Scanner;

/**
 * MIT License
 * (c) 2017 Ricardo Constantino
 */

public class Jurl {
    private boolean outputToFile;

    public static void main(String[] args) {

        Jurl j = new Jurl();

        String urlToGet = null;

        if (args.length > 0) {
            urlToGet = args[0];
        }

        if (urlToGet == null) {
            urlToGet = getString();
        }


        URL url = j.getUrl(urlToGet);

        String content = j.getContent(url);

        System.out.println(content);

    }

    private void outputToFile(boolean b) {
        outputToFile = b;
    }

    private String getContent(URL url) {
        StringBuilder content = new StringBuilder();
        String line = "";

        URLConnection uc = null;
        try {
            uc = url.openConnection();
            uc.setRequestProperty("User-Agent", "curl/7.54.0");
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

        try (BufferedReader in = new BufferedReader(
                new InputStreamReader(uc.getInputStream()))) {
            while ((line = in.readLine()) != null) {

                content.append(line).append("\n");

            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return content.toString();
    }

    private URL getUrl(String url) {
        URL res = null;
        try {
            res = new URL(url);
        } catch (MalformedURLException e) {
            e.printStackTrace();
            System.exit(1);
        }
        return res;
    }

    private static String getString() {
        Scanner scanner = new Scanner(System.in);
        System.out.printf("URL to get: ");
        return scanner.nextLine();
    }
}
