#ifdef _WIN32
#include <winsock2.h>
#else
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include "miinam.h"

HMiinam g_hcam = NULL;
void* g_pImageData = NULL;
unsigned g_total = 0;

static void __stdcall EventCallback(unsigned nEvent, unsigned nPara, void* pCallbackCtx, MiinamEventExtra* pExtra)
{
	if (nEvent == MIINAM_EVENT_IMAGE)
	{
		unsigned w = 0, h = 0;
		if (SUCCEEDED(Miinam_PullImage(g_hcam, g_pImageData, 24, &w, &h)))
			printf("pull image ok, total = %u, %u x %u\n", ++g_total, w, h);
		else
			printf("pull image failed\n");
	}
}

int main(int, char**)
{
	Miinam_Init(EventCallback, NULL);
	printf("wait 5 seconds to discover the online cameras\n");
#ifdef _WIN32
	Sleep(5000);
#else
	sleep(5);
#endif
	MiinamDevice arr[MIINAM_MAX];
    int n = Miinam_Enum(arr, MIINAM_MAX);
    if (n <= 0)
    {
        printf("no camera found\n");
        return -1;
    }
    for (int i = 0; i < n; ++i)
        printf("%s: %s\n", arr[i].model, arr[i].addr);
    g_hcam = Miinam_Open(arr[0].id);
    if (NULL == g_hcam)
    {
        printf("open camera failed\n");
        return -1;
    }
	int w = 0, h = 0;
    if (Miinam_get_Size(g_hcam, &w, &h) < 0)
        printf("failed to get size\n");
    else
    {
        g_pImageData = malloc(TDIBWIDTHBYTES(w * 24) * h);
        if (NULL == g_pImageData)
            printf("failed to malloc\n");
        else
        {
            int ret = Miinam_StartPullModeWithCallback(g_hcam, NULL);
            if (ret < 0)
                printf("failed to start camera, ret = %d\n", ret);
            else
            {
                printf("press ENTER to exit\n");
                getc(stdin);
            }
        }
    }
    
    /* cleanup */
    Miinam_Close(g_hcam);
    if (g_pImageData)
        free(g_pImageData);
	Miinam_Fini();
    return 0;
}
