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

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

#ifndef WINCE
  #define FUNC_NAME "_card_authorize11"
  #define DDL_NAME "pilot_nt.dll"
#else
  #define FUNC_NAME L"card_authorize11"
  #define DDL_NAME L"pilot_nt.dll"
#endif



typedef int (*dynamic_function)(char *track2, struct auth_answer11 *auth_answer);

DWORD polling(dynamic_function function)
{
  auth_answer11 argument;

  memset(&argument,0,sizeof(argument));
  argument.ans.TType = OP_PILOT_START;
  argument.ans.Amount = 10000;
  
  DWORD result = function(NULL,&argument);
  if (result) {
    std::cerr << "OP_PILOT_START failed with code '" << result << "'!" << std::endl;
    return result;
  }

  int count = 100;
  for (result = 3; (result == 3) && count; --count)   // polling in progress
  {
    std::cout << "\r Wait for card " << count << " times...";
    memset(&argument,0,sizeof(argument));
    argument.ans.TType = OP_PILOT_STATUS;
    argument.ans.Amount = 10000;
    result = function(NULL, &argument);
  }

  if ((result == ERR_CARD_READY) || (result == 0))
  {
    std::cout << "Card read succesfully!" << std::endl;
    return ERR_OK;
  }
  else
  {
    memset(&argument,0,sizeof(argument));
    argument.ans.TType = OP_PILOT_STOP;  // close reader
    result = function(NULL, &argument);
  }
  std::cout << "Operation completed with code '" << result << "'!" << 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
{
  HMODULE dll = LoadLibrary(DDL_NAME);
  if (!dll) 
  {
    std::cerr << "pilot_nt.dll not found";
    return -1;
  }

  try {
    dynamic_function function = (dynamic_function)GetProcAddress(dll, FUNC_NAME);
    if (!function)
    {
      std::cerr << "function " << FUNC_NAME << " in " << DDL_NAME << " not found";
      return -2;
    }

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