/***************************** LICENSE START ***********************************

 Copyright 2016 ECMWF and INPE. This software is distributed under the terms
 of the Apache License version 2.0. In applying this license, ECMWF does not
 waive the privileges and immunities granted to it by virtue of its status as
 an Intergovernmental Organization or submit itself to any jurisdiction.

 ***************************** LICENSE END *************************************/

#pragma once

#include <string>

#include <curl/curl.h>  // needed because we use the CURL type in MvNetwork


// ----------------------------------------------------------------------------
// MvNetworkData
// Holds and manages the buffer to store data resulting from a network transfer
// ----------------------------------------------------------------------------

class MvNetworkData
{
public:
    MvNetworkData() :
        buffer_(0),
        pos_(0),
        len_(0),
        initialSize_(10240) {}
    ~MvNetworkData();

    void clear();

    size_t add(char* ptr, size_t size);
    std::string toString();

    char* buffer_;
    size_t pos_;
    size_t len_;
    const size_t initialSize_;
};


// ----------------------------------------------------------------------
// MvNetwork
// Handles the data request and writes the data to the requested location
// ----------------------------------------------------------------------

class MvNetwork
{
public:
    MvNetwork();
    bool get(const std::string&, const std::string&, const std::string, std::string&);
    std::string header() { return header_.toString(); }
    long responseCode() { return responseCode_; }

protected:
    void setupProxy();
    static size_t writeCb(char* ptr, size_t size, size_t nmemb, void* userdata);
    static size_t headerCb(char* ptr, size_t size, size_t nmemb, void* userdata);

    CURL* ch_;
    MvNetworkData data_;
    MvNetworkData header_;
    long responseCode_;
};
