#include <iostream>
#include <vector>
#include "histogram.h"
#include "svg.h"
#include <curl/curl.h>
#include <sstream>
#include <string>

using namespace std;

struct Input {
    vector<double> numbers;
    size_t bin_count{};
};

Input
input_data(istream& stream, bool prompt){
    size_t number_count;
    if (prompt){
        cerr << "Enter number count:" << endl;
    }
    stream >> number_count;
    Input in;
    in.numbers.resize(number_count);
    vector<double> numbers(number_count);
    if (prompt){
        cerr << "Enter numbers:" << endl;
    }
    for (size_t i = 0; i < number_count; i++) {
        stream >> in.numbers[i];
    }
    if (prompt){
        cerr << "Enter bin count:" << endl;
    }
    stream >> in.bin_count;
    return in;
}
size_t
write_data(void* items, size_t item_size, size_t item_count, void* ctx) {
    size_t data_size = item_size * item_count;
    stringstream* buffer = reinterpret_cast<stringstream*>(ctx);
    auto text = reinterpret_cast<const char*>(items);
    buffer->write(text, data_size);
    return data_size;
}

Input
download(const string& address){
    stringstream buffer;
    curl_global_init(CURL_GLOBAL_ALL);
    CURL *curl = curl_easy_init();
        if(curl) {
            CURLcode res;
            double namelookup;
            curl_easy_setopt(curl, CURLOPT_URL, address.c_str());
            curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
            curl_easy_setopt(curl, CURLOPT_WRITEDATA, &buffer);
            res = curl_easy_perform(curl);
            if (res != 0) {
                curl_easy_strerror(res);
                exit(1);
            }
            else {
                res = curl_easy_getinfo(curl, CURLINFO_NAMELOOKUP_TIME, &namelookup);
                if (res != 0) {
                    curl_easy_strerror(res);
                    exit(1);
                }
                else {
                    cerr << "Time: " << namelookup;
                }
            }
            curl_easy_cleanup(curl);
        }
    return input_data(buffer, false);
}

int
main(int argc, char* argv[]) {
    Input input;
    if (argc > 1){
        input = download(argv[1]);
    }
    else{
        input = input_data(cin, true);
    }
    auto bins = make_histogram(input.numbers, input.bin_count);
    show_histogram_svg(bins);
    return 0;
}