#include "reHttpPoller.h"

reHttpPoller::reHttpPoller(const std::string& url, long interval_ms) :
        url_(url),
        interval_(interval_ms){
}

void reHttpPoller::start() {
    is_running_ = true;
    worker_ = std::thread(&reHttpPoller::SendRequests, this);
}

void reHttpPoller::stop() {
    is_running_ = false;
    if (worker_.joinable()) worker_.join();
}

void reHttpPoller::setEndpoint(const std::string &url) {
    this->url_ = url;
}

void reHttpPoller::SendRequests(){
    CURL* curl = curl_easy_init();
    while(is_running_) {
        std::string readBuffer;
        curl_easy_setopt(curl, CURLOPT_URL, url_.c_str());
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
        curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
        curl_easy_setopt(curl, CURLOPT_TIMEOUT, 5);
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L); // отключил проверку ssl сертификата

        CURLcode res = curl_easy_perform(curl);
        if (res != CURLE_OK) {
            std::cerr << "curl_easy_perform() failed: " << curl_easy_strerror(res) << std::endl;
        } else {
            data_ = nlohmann::json::parse(readBuffer);
        }
        std::this_thread::sleep_for(std::chrono::milliseconds(interval_));
    }
    curl_easy_cleanup(curl);
}

size_t reHttpPoller::WriteCallback(void* contents, size_t size, size_t nmemb, void* userp) {
    ((std::string*)userp)->append((char*)contents, size * nmemb);
    return size * nmemb;
}
