#include "xysdk_common.h"
#include "xysdk_log.h"

#include "http/http_cli.h"

int xy_api_http_post_request(char *url, bool is_json, char *post_data, unsigned int data_len, void *response)
{
	http_body_obj http_recv = {0};
	int ret = 0;
	httpcli_ctx ctx = {0};
	http_recv.recv_len = 0;
	http_recv.buf_len = 1024;
	http_recv.buf_count = 1;
	http_recv.p = (char *)malloc(http_recv.buf_len * http_recv.buf_count);
	if (http_recv.p == NULL) {
		ret = -1;
		goto exit;
	}
	ctx.data_format = "application/json";
	ctx.data_len = data_len;
	ctx.post_data = post_data;
	ctx.timeout_millsec = 5000;
	ctx.priv = &http_recv;
	ctx.url = url;
	ctx.connection = "close";
	ret = httpcli_post(&ctx);
	if (ret) {
		ret = -1;
		goto exit;
	}
exit:
	httpcli_close(&ctx);
	if (http_recv.p) {
		/* g_printf("https receive data: >>>>>>>>>>>%s", http_recv.p); */
		free(http_recv.p);
		http_recv.p = NULL;
	}
	return ret;
}




int xy_api_http_get_request(char *url, void *response)
{
	int error = 0;
	http_body_obj http_body_buf;
	XYHttpResponseData *response_buff=(XYHttpResponseData *)response;
	printf("wt get url: %s\n", url);
	httpcli_ctx *ctx = (httpcli_ctx *)calloc(1, sizeof(httpcli_ctx));
	if (!ctx) {
		printf("calloc faile\n");
		return -1;
	}
	memset(&http_body_buf, 0x0, sizeof(http_body_obj));
	http_body_buf.recv_len = 0;
	http_body_buf.buf_len = 2 * 1024;
	http_body_buf.buf_count = 1;
	http_body_buf.p = (char *)malloc(http_body_buf.buf_len * http_body_buf.buf_count);
	if (!http_body_buf.p) {
		free(ctx);
		ctx = NULL;
		return -1;
	}
	ctx->url=url;
	ctx->timeout_millsec=8000;
	ctx->priv=&http_body_buf;
	ctx->connection="close";
	ctx->data_format="application/json";
	ctx->post_data=response;
	ctx->data_len=strlen(response);
	error = httpcli_get(ctx);
	if (error != HERROR_OK) {
		printf("func  %s himalaya test failed\n",__FUNCTION__);
	} else {

		if(http_body_buf.recv_len>0)
		{
			printf("\nrecieve %d bytes from(%s)\n",http_body_buf.recv_len,url);
			strncpy(response_buff->data,http_body_buf.p,http_body_buf.recv_len);
			/* printf(">>>>>response %s ",response_buff->data); */
			response_buff->length=strlen(response_buff->data);
			/* printf("%s\n",http_body_buf.p); */
		}
	}
	free(http_body_buf.p);
	free(ctx);
	return error;
}