//
//
//
//			POSNET BASE EXAMPLES
//			EXAMPLE ASYNC EVENT
//
//

#include <stdlib.h>
#include <string>
#include <iostream>
#include <istream>
#include <limits>
#ifdef WIN32
#include <windows.h>
#else
#include <pthread.h>
#include <semaphore.h>
#endif
#include "../../include/posnet.h"
#include "../../include/posnet_hlapi.h"

using namespace std;



int main(int argc, char *argv[])
{

#ifdef WIN32
	WSADATA WSAData;
	if (WSAStartup (MAKEWORD(2,0), &WSAData) != 0) 
	{
		MessageBox (NULL, TEXT("WSAStartup failed!"), TEXT("Error"), MB_OK);
		return FALSE;
	}

#endif  
  
#include "../setup.inc"


#ifdef WIN32
	POS_SetEventHandlingMode(hLocalDevice,POSNET_EVENT_EVENT);
	HANDLE event=POS_GetEvent(hLocalDevice);
#else
	POS_SetEventHandlingMode(hLocalDevice,POSNET_EVENT_SEMAPHORE);
	sem_t *event=(sem_t*)POS_GetSemaphore(hLocalDevice);
#endif

	int mode=-1;
	while (mode<0 || mode>1)
	{
		cout << "Prosze wybra tryb: 0-Manual, 1-DB" ;
		cin >> mode;
	}

	while (1) 
	{
		
#ifdef WIN32		
		if (WaitForSingleObject(event,1000)==WAIT_OBJECT_0)
		{
			ResetEvent(event);
#else
		if (sem_wait(event)==0)
		{
#endif
			POSNET_HANDLE ps=POS_PopAsyncData(hLocalDevice,1);
			char buffer[64];
			if (POSG_CardInfo(ps,buffer)==POSNET_STATUS_OK)
			{
				POSNET_HANDLE rq;
				POSNET_STATUS pstat;
				
				if (mode)
					pstat=POSS_DBDiscntPCSet(hLocalDevice,&rq,0,1,POSNET_REQMODE_SPOOL);
					else
					pstat=POSS_ManualDiscntPCSet(hLocalDevice,&rq,0,"FRIEND1",0x11,"100",1,1,POSNET_REQMODE_SPOOL);
				if (pstat!=POSNET_STATUS_OK)
				{
					cout << "Setting Manual discount failed - function error : 0x" << hex << pstat << dec << endl;
				}
				else
				{
					cout << "Setting Manual discount" << endl;
					int x=30;
					while (POS_WaitForRequestCompleted(rq,1000)!=POSNET_STATUS_OK)
					{
						cout << "Still waiting for answer ...." << endl;
						if (!x--) break;
					}
					if (POS_GetRequestState(rq)==POSNET_RSTATE_COMPLETED)
					{
						cout << "Answer for setup received : ";
						pstat=POS_GetRequestStatus(rq);
						cout << "0x" << hex << pstat << dec << endl;
					}
					POSG_Default(rq);
				}

			}
			else
				cout << "POSG_CardInfo Failed....." << endl;
		}
		else
		{
			cout << "No card ....." << endl;
		}
	}

	POS_CloseDevice(hLocalDevice);
	POS_DestroyDeviceHandle(hDevice);
	return 0;
}
