#include <windows.h>
#include <iostream>
#include <vector>
#include <fstream>
#include <ctime>

#include "..\..\..\..\pilot_nt.h"
#include "..\..\..\..\deprtmnt.h"

#ifndef WINCE
  #define FUNC_AUTH "_card_authorize6_ext"  
  #define DLL_NAME "pilot_nt.dll"
#else
  #define FUNC_AUTH L"card_authorize6_ext"
  #define DLL_NAME L"pilot_nt.dll"
#endif

#define CHEQUE_FILENAME "cheque.txt"

extern HMODULE LoadPilotNt(const char* name, const char** nameOfTheUncknownFunction);
extern void    FreePilotNt(HMODULE dll);

DWORD payment_with_requisites(const char *rrn, char *tagValue, DWORD paymentTag)
{
	payment_info_item infoItem;
	auth_answer6 argument;

	memset(&infoItem, 0, sizeof(infoItem));
	memset(&argument, 0, sizeof(argument));
	// fill argument
	argument.auth_answ.TType = OP_SEND_TICKETS;
	if (rrn)
	{
		strcpy(argument.RRN, rrn);
	}
	// fill payment info item
	infoItem.dwTag = paymentTag;
	if (tagValue)
	{
		strcpy(infoItem.Value, tagValue);
	}
	infoItem.pNextItem = NULL;

	DWORD result = card_authorize6_ext(NULL, &argument, &infoItem);
	std::cout << "Payment with requisites finished with code '" << result << "'. RRN:" << argument.RRN << std::endl;

	return result;
}

#ifndef WINCE
int main (int argc, char** argv)
#else
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nShowCmd)
#endif
{
  //_CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG)|_CRTDBG_LEAK_CHECK_DF|_CRTDBG_ALLOC_MEM_DF);

	const char *nameOfTheUncknownFunction = NULL;
	HMODULE dll = LoadPilotNt(DLL_NAME, &nameOfTheUncknownFunction);
	if (!dll) 
	{
		std::cerr << DLL_NAME << " not found";
		return -1;
	}
  srand(time(NULL));
	try 
	{
    int count=0;

    if (argc>1)
      count = atoi(argv[1]);

    if (!count)
    {
      std::cout<<"Usage: mcd_test <number of operation>. Start 2000 operations"<<std::endl; 
      count = 2000;
    }

    for (int i=0; i<count; i++)
    {

      auth_answer6 argument;
      memset(&argument, 0, sizeof(argument));

	    // fill argument
	    argument.auth_answ.TType = OP_PURCHASE;
      argument.auth_answ.Amount=rand() % 100000;
      int rc = card_authorize6_ext(NULL, &argument, NULL);

      std::cout<< "Operation:" << i+1<<"\tAmount:"<<argument.auth_answ.Amount<<"\tResult:"<<rc<<std::endl;

      if (argument.auth_answ.Check)
        GlobalFree(argument.auth_answ.Check);
    }

	}
	catch(...)
	{
		
	}
  FreeLibrary(dll);
	return 0;
}
