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

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

#ifndef WINCE
#define FUNC_AUTH "_card_authorize6_ext"
#define DDL_NAME "pilot_nt.dll"
#else
#define FUNC_AUTH L"card_authorize6_ext"
#define FUNC_MULTI_AUTH_COMPLETE "card_complete_multi_auth8"
#define DDL_NAME L"pilot_nt.dll"
#endif

#define CHEQUE_FILENAME "cheque.txt"

//typedef int (*dynamic_card_auth)(char *track2, struct auth_answer8 *auth_answer);
typedef int (*dynamic_card_auth6_ext)(char* track2, auth_answer6* auth_answer, payment_info_item* payinfo);

DWORD payment_with_requisites(dynamic_card_auth6_ext card_auth, DWORD amount, char* vTagValue, DWORD vPaymentTag)
{
	payment_info_item InfoItem;
	auth_answer6	  argument;

	memset(&argument, 0, sizeof(argument));
	argument.auth_answ.TType = OP_PURCHASE;
	argument.auth_answ.Amount = amount;

	memset(&InfoItem, 0, sizeof(InfoItem));
	if (vPaymentTag)
		InfoItem.dwTag = vPaymentTag;
	if (vTagValue)
		strcpy(InfoItem.Value, vTagValue);
	InfoItem.pNextItem = NULL;

	DWORD result = card_auth(NULL, &argument, &InfoItem);

	std::cout << "Payment with requisites finished with code '" << result << "'. RRN:" << argument.RRN << std::endl;
	return result;
}

/*DWORD few_complete_auth(dynamic_card_complete_multi_auth8 card_complete_multi_auth, DWORD summaryAmount, char* encryptedData, preauth_rec* completions, int count)
{
  auth_answer8 argument;

  memset(&argument,0,sizeof(argument));
  argument.auth_answ.TType = OP_COMPLETION;
  argument.auth_answ.Amount = summaryAmount;
  strcpy(argument.EncryptedData, encryptedData);

  DWORD result = card_complete_multi_auth(NULL,&argument, completions, count);

  std::cout << "Authorization completion finished with code '" << result << "'" << std::endl;

  std::ofstream file(CHEQUE_FILENAME);
  file << argument.auth_answ.Check;
  file.close();

  if (argument.auth_answ.Check) {
	std::cout << "Cheque saved to file " << CHEQUE_FILENAME << std::endl;
	//GlobaFree(argument.auth_answ.Check);
  }
  return result;
}*/

#ifndef WINCE
int main(int argc, char** argv)
#else
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nShowCmd)
#endif
{
	HMODULE dll = LoadLibrary(DDL_NAME);
	if (!dll)
	{
		std::cerr << "pilot_nt.dll not found";
		return -1;
	}

	try
	{
		dynamic_card_auth6_ext card_auth6_ext = (dynamic_card_auth6_ext)GetProcAddress(dll, FUNC_AUTH);

		if (!card_auth6_ext)
		{
			std::cerr << "card_auth " << FUNC_AUTH << " in " << DDL_NAME << " not found" << std::endl;
			return -2;
		}

		payment_with_requisites(card_auth6_ext, 10000, "qerwt1234", 0x5F66);
	}
	catch (...)
	{
		std::cerr << "Unhandled exception" << std::endl;
	}

	FreeLibrary(dll);
	return 0;
}