/***************************** 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 *************************************/

#ifndef MVNETWORK_H
#define MVNETWORK_H


#include <string.h>
#include <curl/curl.h>  // needed because we use the CURL type in MvNetwork
using std::string;


// ----------------------------------------------------------------------------
// 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);
    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 string&, const string&, const string, string&);
    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_;
    string outFile_;
    MvNetworkData data_;
    MvNetworkData header_;
    long responseCode_;
};


#endif  //MVNETWORK_H
