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

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

#ifndef WINCE
  #define FUNC_NAME "_AskCardHolderAbout"
  #define DDL_NAME "pilot_nt.dll"
#else
  #define FUNC_NAME L"AskCardHolderAbout"
  #define DDL_NAME L"pilot_nt.dll"
#endif



typedef int (*dynamic_function)(const char* question, char* answer, unsigned answerLength);

DWORD ask(dynamic_function function)
{
  char answer[100];

  DWORD result = function("Question?", answer, sizeof(answer));

  std::cout << "Operation completed with code '" << result << "'. Answer:" << answer << std::endl;
  return result;
}

DWORD ask_email(dynamic_function function)
{
  char answer[100];

  DWORD result = function("email", answer, sizeof(answer));

  std::cout << "Operation completed with code '" << result << "'. Answer:" << answer << std::endl;
  return result;
}

DWORD retry_ask_email_for_incorrect_name(dynamic_function function)
{
  char answer[100] = "sbe!bank";

  DWORD result = function("email", answer, sizeof(answer));

  std::cout << "Operation completed with code '" << result << "'. Answer:" << answer << std::endl;
  return result;
}

DWORD retry_ask_email_for_incorrect_domain(dynamic_function function)
{
  char answer[100] = "sberbank@sber!ank.ru";

  DWORD result = function("email", answer, sizeof(answer));

  std::cout << "Operation completed with code '" << result << "'. Answer:" << answer << std::endl;
  return result;
}

DWORD ask_phone(dynamic_function function)
{
  char answer[100];

  DWORD result = function("phone", answer, sizeof(answer));

  std::cout << "Operation completed with code '" << result << "'. Answer:" << answer << std::endl;
  return result;
}

DWORD retry_ask_phone(dynamic_function function)
{
  char answer[100] = "+71231234567";

  DWORD result = function("phone", answer, sizeof(answer));

  std::cout << "Operation completed with code '" << result << "'. Answer:" << answer << 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;
    }

    ask(function);
    ask_email(function);
    retry_ask_email_for_incorrect_name(function);
    retry_ask_email_for_incorrect_domain(function);
    ask_phone(function);
    retry_ask_phone(function);
  }
  catch(...)
  {
	  std::cerr << "Unhandled exception" << std::endl;
  }
  FreeLibrary(dll);
  return 0;
}