#include <iostream>
#include <vector>
#inclide <cmath>
#invlude <string>
#include "histogram.h"
#include "text.h"
#include <conio.h>
#include "histogram_internal.h"
#include <curl/curl.h>
#include <sstream>
#include "svg.h"


using namespace std;

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

Input
input_data(istream &sin, bool promt)
{
    Input in;
    size_t number_count;

    if (promt)
    {
        cerr << "enter number count";
    }
    sin>> number_count;


    in.numbers.resize(number_count);
    for (size_t i = 0; i < number_count; i++)
    {
        sin>> in.numbers[i];
    }

    if (promt)
    {
        cerr<<"enter bin count:";
    }
    sin >>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);
    buffer->write(reinterpret_cast<const char*>(items), data_size);
    return data_size;
}

Input
download(const string& adress)
{
    stringstream buffer;
    CURL* curl = curl_easy_init();
    if(curl)
    {
        CURLcode res;
        curl_easy_setopt(curl, CURLOPT_URL, adress.c_str());
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA,&buffer);
        res=curl_easy_perform(curl);
        curl_easy_cleanup(curl);


        if(res!=CURLE_OK)
        {
            cout<<curl_easy_strerror;
            exit(1);
        }
        if(res== CURLE_ok)
        {
            res=curl_easy_getinfo(curl, CURLINFO_CONNECT_TIME, &connect);
            if(CURLE_OK ==res)
            {
                cerr<<"connecting time: "<<connect;
            }
        }
        curl_easy_cleanup(curl);
    }

    return input_data(buffer, false);
}


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