#define INDEV	stdin
#define OUTDEV	stdout

#define DEFAULT_BUF_SIZE	1024
#define RESERVED		5

#include <time.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include "SHSSDK.h"
#include "SHCSDK.h"

int main(void)
{
	char service[DEFAULT_BUF_SIZE + RESERVED];
	char path[DEFAULT_BUF_SIZE + RESERVED];
	char service_host[DEFAULT_BUF_SIZE + RESERVED];
	char auth_string[DEFAULT_BUF_SIZE + RESERVED];
	char *auth_key, *auth_file;
	char *__service_host = NULL;
	char *__auth_string = NULL;
	HSHSDK hsdk;
	HSHFILELIST hsdf;
	int i;
	PSHFILE_STRUCT pshf;

	/* get service id */
	strcpy(service, "solboxtest");
	if (service && !strcmp(service, "solboxtest")) {
		auth_key = "solboxtest";
		auth_file = "./solboxtest186.cert";
	} else {
		fprintf(OUTDEV, "서비스 ID가 존재하지 않습니다.\n");
		goto exit_prg;
	}

	/* SSDK : get service host */
	__service_host = (char *)sh_get_service_host("solboxtest", "solboxtest", service);
	if (!__service_host) {
		fprintf(OUTDEV, "서비스 호스트를 받아오지 못했습니다.\n");
		goto exit_prg;
	}

	/* SSDK : get auth string */
	__auth_string = (char *)sh_get_auth_string("solboxtest", "solboxtest", service, auth_key, auth_file, time(0)+100000);
 	if (!__auth_string) {
		fprintf(OUTDEV, "인증 스트링을 받아오지 못했습니다.\n");
		goto exit_prg;
	}
	snprintf(service_host, DEFAULT_BUF_SIZE, "%s",
		__service_host);

	snprintf(auth_string, DEFAULT_BUF_SIZE, "%s",
		__auth_string);

	/* CSDK : init */
	fprintf(stderr, "service_host %s\n", service_host);
	hsdk = sh_init(service_host, auth_string, NULL, NULL);
	if (hsdk == NULL) {
		fprintf(OUTDEV, "클라이언트 SDK 초기화를 실패하였습니다.\n");
		goto exit_prg;
	}

	path[0] = '\0';
	/* TODO : listing base uri copy to path */
	strcpy(path, "/");

	/* CSDK : get list */
	hsdf = sh_get_filelist(hsdk, path, 1);
	if (hsdf == NULL) {
		fprintf(OUTDEV, "파일 리스트 수신을 실패하였습니다.\n");
		goto exit_prg;
	}
	for (i = 0; i < sh_get_filelist_count(hsdk, hsdf); i++) {
		pshf = sh_get_file(hsdk, hsdf, i);
		if (pshf->attr == SHFILEATTR_FOLDER) {
			fprintf(OUTDEV, "폴더명 : %s\n", pshf->path);
		} else {
			fprintf(OUTDEV, "파일명 : %s (%lld byte)\n",
				pshf->path, pshf->size);
		}
	}

exit_prg:
	if (__service_host) free(__service_host);
	if (__auth_string) free(__auth_string);

	return 0;
}
