#include <QtCore/QDebug>

#include <network.h>
#pragma execution_character_set("utf-8")

namespace LAMPMainWidget {

size_t
writeData(void *content, size_t size, size_t nmemb, void *userp) {
  size_t realSize{size * nmemb};
  auto userRes = static_cast<QByteArray *>(userp);
  if (!userRes) {
    qDebug() << "无效的数据存储对象";
    return 0;
  }
  userRes->append(static_cast<char *>(content), int(realSize));

  return realSize;
}

const QString Network::kUserAgent{"Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0"};

QByteArray
Network::httpRequest(const QString &url) {
  QByteArray result{};
  if (url.isEmpty()) {
    qDebug() << QString("url为空");
    return result;
  }

  CURL *curl = curl_easy_init();
  if (!curl) {
    qDebug() << "无法初始化curl句柄";
    return result;
  }

  curl_easy_setopt(curl, CURLOPT_URL, url.toStdString().c_str());
  curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writeData);
  curl_easy_setopt(curl, CURLOPT_WRITEDATA, &result);
  curl_easy_setopt(curl, CURLOPT_USERAGENT, kUserAgent.toStdString().c_str());

  CURLcode res = curl_easy_perform(curl);
  if (CURLE_OK != res) {
    qDebug() << QString("%1 =>请求异常, %2").arg(url).arg(curl_easy_strerror(res));
    result.clear(); // 请求失败时，清空接受到的数据
  }

  curl_easy_cleanup(curl);

  return result;
}

QByteArray
Network::httpsRequest(const QString &url) {
  QByteArray result{};
  if (url.isEmpty()) {
    qDebug() << QString("url为空");
    return result;
  }

  CURL *curl = curl_easy_init();
  if (!curl) {
    qDebug() << "无法初始化curl句柄";
    return result;
  }

  curl_easy_setopt(curl, CURLOPT_URL, url.toStdString().c_str());
  curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writeData);
  curl_easy_setopt(curl, CURLOPT_WRITEDATA, &result);
  curl_easy_setopt(curl, CURLOPT_USERAGENT, kUserAgent.toStdString().c_str());
  curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
  curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);

  CURLcode res = curl_easy_perform(curl);
  if (CURLE_OK != res) {
    qDebug() << QString("%1 =>请求异常, %2").arg(url).arg(curl_easy_strerror(res));
    result.clear(); // 请求失败时，清空接受到的数据
  }

  curl_easy_cleanup(curl);

  return result;
}

}
