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

using namespace std;

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

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
input_data(istream& in, bool prompt)
{
    if(prompt)
        cerr << "vvedite col-vo nomerov:";
    size_t number_count;
    in >> number_count;
    Input rez;

    if(prompt)
        cerr << "vvedite nomera:";
    rez.numbers.resize(number_count);
    for (size_t i = 0; i < number_count; i++)
    {
        in >> rez.numbers[i];
    }
    if(prompt)
        cerr << "vvedite col-vo corzin:";
    in >> rez.bin_count;
    return rez;
}

Input
download(const string& address) {
    stringstream buffer;

    CURL* curl = curl_easy_init();
    if(curl)
    {
        CURLcode res;
        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)
            {
            cout << curl_easy_strerror(res);
            exit(1);
            }

        curl_easy_cleanup(curl);
    }
    return input_data(buffer, false);
}

int
main(int argc, char* argv[])
{

    int ind;
    const char* format;
    Input input;
    if (argc > 1)
    {
        for (int i = 0; i < argc; i++)
        {
            if (strcmp(argv[i], static_cast<const char*>("-format")) == 0)
            {
                ind = i;
            }
        }

        if ((ind+1) < argc)
        {
            format = argv[ind + 1];
            if (!(strcmp(format, static_cast<const char*>("text")) == 0) && !(strcmp(format, static_cast<const char*>("svg")) == 0))
            {
                cout << "unknown format";
                return 0;
            }
        }
        else
        {
            cout << "write program format";
            return 0;
        }
        input = download(argv[1]);
    }
    else
    {
        input = input_data(cin, true);
    }

    const auto bins = make_histogram(input.numbers, input.bin_count);

    if (strcmp(format, static_cast<const char*>("text")) == 0) {
    show_histogram_text(bins, input.numbers, input.bin_count); }
    else if (strcmp(format, static_cast<const char*>("svg")) == 0) {
    show_histogram_svg(bins); }
}