/*
 *  TOPPERS ECHONET Lite Communication Middleware
 * 
 *  Copyright (C) 2016 Cores Co., Ltd. Japan
 * 
 *  上記著作権者は，以下の(1)〜(4)の条件を満たす場合に限り，本ソフトウェ
 *  ア（本ソフトウェアを改変したものを含む．以下同じ）を使用・複製・改
 *  変・再配布（以下，利用と呼ぶ）することを無償で許諾する．
 *  (1) 本ソフトウェアをソースコードの形で利用する場合には，上記の著作
 *      権表示，この利用条件および下記の無保証規定が，そのままの形でソー
 *      スコード中に含まれていること．
 *  (2) 本ソフトウェアを，ライブラリ形式など，他のソフトウェア開発に使
 *      用できる形で再配布する場合には，再配布に伴うドキュメント（利用
 *      者マニュアルなど）に，上記の著作権表示，この利用条件および下記
 *      の無保証規定を掲載すること．
 *  (3) 本ソフトウェアを，機器に組み込むなど，他のソフトウェア開発に使
 *      用できない形で再配布する場合には，次のいずれかの条件を満たすこ
 *      と．
 *    (a) 再配布に伴うドキュメント（利用者マニュアルなど）に，上記の著
 *        作権表示，この利用条件および下記の無保証規定を掲載すること．
 *    (b) 再配布の形態を，別に定める方法によって，TOPPERSプロジェクトに
 *        報告すること．
 *  (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損
 *      害からも，上記著作権者およびTOPPERSプロジェクトを免責すること．
 *      また，本ソフトウェアのユーザまたはエンドユーザからのいかなる理
 *      由に基づく請求からも，上記著作権者およびTOPPERSプロジェクトを
 *      免責すること．
 * 
 *  本ソフトウェアは，無保証で提供されているものである．上記著作権者お
 *  よびTOPPERSプロジェクトは，本ソフトウェアに関して，特定の使用目的
 *  に対する適合性も含めて，いかなる保証も行わない．また，本ソフトウェ
 *  アの利用により直接的または間接的に生じたいかなる損害に関しても，そ
 *  の責任を負わない．
 * 
 *  @(#) $Id$
 */
#include <lib/curl_setup.h>
#include <curl/curl.h>
#include <wolfssl/wolfcrypt/wc_port.h>
#include <wolfssl/ssl.h>
#include <lwip/sockets.h>
#include <string.h>
#include "main.h"
#include "kernel_cfg.h"
#include "ff.h"

#define SKIP_PEER_VERIFICATION
//#define SKIP_HOSTNAME_VERIFICATION
char response[80];

void client_init(void)
{
	uITRON4_minit(ITRON_POOL_SIZE);

	curl_global_init(CURL_GLOBAL_DEFAULT);
}

size_t write_data(void *buffer, size_t size, size_t nmemb, void *userp)
{
	int rest = size * nmemb;
	int len;

	while (rest > 0) {
		len = rest;
		if (len > (sizeof(response) - 1)) {
			len = sizeof(response) - 1;
		}

		memcpy(response, buffer, len);

		response[len] = '\0';

		syslog(LOG_NOTICE, response);

		dly_tsk(100);

		rest -= len;
		(char *)buffer += len;
	}

	return size * nmemb;
}

size_t read_data(char *buffer, size_t size, size_t nitems, void *instream)
{
	FIL *file = (FIL *)instream;
	UINT ret = 0;
	FRESULT res;

	res = f_read(file, buffer, size * nitems, &ret);
	if (res != FR_OK)
		return 0;

	int rest = ret;
	int len;

	while (rest > 0) {
		len = rest;
		if (len > (sizeof(response) - 1)) {
			len = sizeof(response) - 1;
		}

		memcpy(response, buffer, len);

		response[len] = '\0';

		syslog(LOG_NOTICE, response);

		dly_tsk(100);

		rest -= len;
		(char *)buffer += len;
	}

	return ret;
}

char errbuf[CURL_ERROR_SIZE];

static void get_logfname(char *fname)
{
	// fname = "0:/log/2016010100000000.log"
	time_t t;
	struct tm tm;
	int tmp1, tmp2;
	char *pos = &fname[7];

	sys_time(&t);
	gmtime_r(&t, &tm);

	/* 年 */
	tmp1 = 1900 + tm.tm_year;
	tmp2 = tmp1 / 1000;
	tmp1 -= tmp2 * 1000;
	*pos++ = '0' + tmp2;
	tmp2 = tmp1 / 100;
	tmp1 -= tmp2 * 100;
	*pos++ = '0' + tmp2;
	tmp2 = tmp1 / 10;
	tmp1 -= tmp2 * 10;
	*pos++ = '0' + tmp2;
	*pos++ = '0' + tmp1;
	/* 月 */
	tmp1 = tm.tm_mon + 1;
	tmp2 = tmp1 / 10;
	tmp1 -= tmp2 * 10;
	*pos++ = '0' + tmp2;
	*pos++ = '0' + tmp1;
	/* 日 */
	tmp1 = tm.tm_mday;
	tmp2 = tmp1 / 10;
	tmp1 -= tmp2 * 10;
	*pos++ = '0' + tmp2;
	*pos++ = '0' + tmp1;
	/* 時 */
	tmp1 = tm.tm_hour;
	tmp2 = tmp1 / 10;
	tmp1 -= tmp2 * 10;
	*pos++ = '0' + tmp2;
	*pos++ = '0' + tmp1;
	/* 分 */
	tmp1 = tm.tm_min;
	tmp2 = tmp1 / 10;
	tmp1 -= tmp2 * 10;
	*pos++ = '0' + tmp2;
	*pos++ = '0' + tmp1;
	/* 秒 */
	tmp1 = tm.tm_sec;
	tmp2 = tmp1 / 10;
	tmp1 -= tmp2 * 10;
	*pos++ = '0' + tmp2;
	*pos++ = '0' + tmp1;
}

static FRESULT write_log(char *fname)
{
	FIL file;
	FRESULT ret;

	ret = f_open(&file, fname, FA_CREATE_ALWAYS | FA_WRITE);
	if (ret != FR_OK) {
		syslog(LOG_ERROR, "not open a upload file %d", ret);
		return ret;
	}

	f_printf(&file, "{\"datetime\":\"");
	for (int i = 7; i < 21; i++)
		f_putc(fname[i], &file);
	f_printf(&file, "\",");

	for (int i = 0; i < 6; i++) {
		struct watt_hour_meter_t *meter = &electric_energy_meter_data[i];
		uint32_t *log;
		int len;

		f_printf(&file, "\"channel%d\":[", i + 1);

		wai_sem(MAIN_SEMAPHORE);

		len = 48 - meter->current_pos;
		if (len > 0) {
			log = &meter->integral_electric_energy_measurement_log[meter->current_pos];
			for (int j = 1; j < len; j++) {
				f_printf(&file, "%d,", *log);
			}
			f_printf(&file, "%d", *log);
		}
		len = 48 - len;
		if (len > 0) {
			f_putc(',', &file);

			log = &meter->integral_electric_energy_measurement_log[0];
			for (int j = 1; j < len; j++) {
				f_printf(&file, "%d,", *log);
			}
			f_printf(&file, "%d", *log);
		}

		sig_sem(MAIN_SEMAPHORE);

		f_putc(']', &file);
		if (i != 5) {
			f_putc(',', &file);
		}
	}

	f_putc('}', &file);

file_close:
	f_close(&file);

	return FR_OK;
}

void client_task(intptr_t exinf)
{
	CURL *curl;
	CURLcode res;
	int error = 0;
	//const char *data = "{\"value\":\"data post\"}";
	struct curl_slist *list = NULL;
	FIL file;
	FRESULT ret;
	char fname[] = {"0:/log/20160101000000.log"};

	get_logfname(fname);

	ret = write_log(fname);
	if (ret != FR_OK) {
		syslog(LOG_ERROR, "log file write error %d", ret);
		return;
	}

	ret = f_open(&file, fname, FA_READ);
	if (ret != FR_OK) {
		syslog(LOG_ERROR, "log file open error %d", ret);
		return;
	}

	syslog(LOG_NOTICE, "cURL start");

	curl = curl_easy_init();
	if (curl == NULL) {
		syslog(LOG_ERROR, "curl_easy_init() failed\n");
		goto file_close;
	}

	/* ask libcurl to show us the verbose output */
	curl_easy_setopt(curl, CURLOPT_VERBOSE, true);

	res = curl_easy_setopt(curl, CURLOPT_URL, "https://www.example.com/");
	if (res != CURLE_OK)
		syslog(LOG_ERROR, "CURLOPT_URL failed: %s\n",
			curl_easy_strerror(res));

	/* set the error buffer as empty before performing a request */
	errbuf[0] = 0;

	/* provide a buffer to store errors in */
	curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errbuf);

#ifdef SKIP_PEER_VERIFICATION
	/*
	* If you want to connect to a site who isn't using a certificate that is
	* signed by one of the certs in the CA bundle you have, you can skip the
	* verification of the server's certificate. This makes the connection
	* A LOT LESS SECURE.
	*
	* If you have a CA cert for the server stored someplace else than in the
	* default bundle, then the CURLOPT_CAPATH option might come handy for
	* you.
	*/
	res = curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
	if (res != CURLE_OK)
		syslog(LOG_ERROR, "CURLOPT_SSL_VERIFYPEER failed: %s\n",
			curl_easy_strerror(res));
#else
	res = curl_easy_setopt(curl, CURLOPT_CAINFO, "0:/certs/ca-cert.pem");
	if (res != CURLE_OK)
		syslog(LOG_ERROR, "CURLOPT_CAINFO failed: %s\n",
			curl_easy_strerror(res));

	res = curl_easy_setopt(curl, CURLOPT_SSLCERT, "0:/certs/client-cert.pem");
	if (res != CURLE_OK)
		syslog(LOG_ERROR, "CURLOPT_SSLCERT failed: %s\n",
			curl_easy_strerror(res));

	res = curl_easy_setopt(curl, CURLOPT_SSLKEY, "0:/certs/client-key.pem");
	if (res != CURLE_OK)
		syslog(LOG_ERROR, "CURLOPT_SSLKEY failed: %s\n",
			curl_easy_strerror(res));
#endif

#ifdef SKIP_HOSTNAME_VERIFICATION
	/*
	* If the site you're connecting to uses a different host name that what
	* they have mentioned in their server certificate's commonName (or
	* subjectAltName) fields, libcurl will refuse to connect. You can skip
	* this check, but this will make the connection less secure.
	*/
	res = curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
	if (res != CURLE_OK)
		syslog(LOG_ERROR, "CURLOPT_SSL_VERIFYHOST failed: %s\n",
			curl_easy_strerror(res));
#endif

	/*res = curl_easy_setopt(curl, CURLOPT_PROXY, "https://proxy.example.com:8080");
	if (res != CURLE_OK)
		syslog(LOG_ERROR, "CURLOPT_PROXY failed: %s\n",
			curl_easy_strerror(res));*/

	curl_easy_setopt(curl, CURLOPT_POST, 1);

	/* size of the POST data */
	//curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, strlen(data));
	curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, file.fsize);

	/* pass in a pointer to the data - libcurl will not copy */
	//curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data);

	list = curl_slist_append(list, "Content-Type: application/json");

	curl_easy_setopt(curl, CURLOPT_HTTPHEADER, list);

	curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&error);

	curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);

	/* now specify which file to upload */
	curl_easy_setopt(curl, CURLOPT_READDATA, &file);

	/* we want to use our own read function */
	curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_data);

	syslog(LOG_NOTICE, "cURL perform the request");
	tslp_tsk(100);

	/* Perform the request, res will get the return code */
	res = curl_easy_perform(curl);
	/* Check for errors */
	if (res != CURLE_OK) {
		syslog(LOG_ERROR, "curl_easy_perform() failed: %s\n",
			curl_easy_strerror(res));
		syslog(LOG_ERROR, errbuf);
	}

	/* always cleanup */
	curl_easy_cleanup(curl);

	syslog(LOG_NOTICE, "cURL end");

file_close:
	f_close(&file);
}

void client_fin(void)
{
	curl_global_cleanup();
}
