// Copyright (C) 2003-2026, Foxit Software Inc..
// All Rights Reserved.
//
// http://www.foxitsoftware.com
//
// The following code is copyrighted and contains proprietary information and trade secrets of Foxit Software Inc..
// You cannot distribute any part of Foxit PDF SDK to any third party or general public,
// unless there is a separate license agreement with Foxit Software Inc. which explicitly grants you such rights.
//
// This file contains an example to demonstrate how to use Foxit PDF SDK to do full text search in PDF documents under a folder.

// Include Foxit SDK header files.
#include <time.h>
#include <direct.h>
#include <stdio.h>
#include <stdlib.h>

#include "../../../include/fs_basictypes_c.h"
#include "../../../include/fs_common_c.h"
#include "../../../include/fs_pdfdoc_c.h"
#include "../../../include/fs_pdfpage_c.h"
#include "../../../include/fs_fulltextsearch_c.h"

#ifndef TRUE
#define TRUE 1
#endif

#ifndef FALSE
#define FALSE 0
#endif

#ifndef NULL
#define NULL (void*)0
#endif

#define MAX_FILE_PATH 260

static const char* sn = "bPxThFlBAYifO3yiW0C51bKbjPap1zHaf5aG5sX378TjFvB7Q0802A==";
static const char* key = "8f3g1sGNtR8NAgfSNv+BvaJWy2fnrw36NZvzh8GUxYXvs+/YczAk4e34yqlOnmL4asgxGMO7+rlOcSHUSSKagx5g4G7VEXfkYLXnDDx77FOOedZPrFFcOCu1vT4+wOKzy1zkORq9cKtiFf44byH5sfRqf+OvELjep2teT9eF9yPCsSw2vRKljXlPy40DMP9XX1O5OTe+mSG3RvwKUMb0+RpG3YobM87j+/ynTDlJMMXw4vgwuTb1ZuAtlvkTdFz7HDLV81C6TYnn73ddHeGD3qYWBVsD4uJkDwyyH/SWr7QX0HSgVg8HSZqnab1VGdAUYxKY2vGWeOTJdu6qDGb5ZEb9O3kZZg+9LYAmUKzDfCYwfIsYZ8Y9LPC4wMx70kIq7JpNnzPvigrdshV8/ew1F0+qP/P5Z1EB53vDVrp2LVSuL873Wv4g3PzjZlNH+1qgT87hC+Buto4qsSUfP5Y2z0uApu+c/TfttCXbeMLSsw9TY1HQD3mkrZExMaQqRrAuXAcZWdvBnVuG3DCZmm8q0DLxJiCfYfViAU/AkbeKMIGaTJdrvIXBcssfde4nmU6qr0M4x4+Hs2ESddtY2QRtLAUBq/7h7GJlJHkEZr8ueaUy/6D/2vvAWz6wMLgmjlPbDTLqzfnCJylHCPtcJmu1SPPT9v1VreBX3+zNWcIT8HueyHEiUniqzwWkRKaotrnNb/zhnHLPpgaBSwKjyi8rOzzVwu/nY84G9ye4jsVjmkIRItKDrW7z22iS+QQuTwfqLVuMB0OD4jMkPCC2slzPfEeZnuh4+Rewln2qLRJVgI72zJ20OBWAelGSpO1Ii2Y3gOvojdmtUwx6R3Z1qFNWTTB25o9ytcux8BLOtTCkA8T8xaT4N339OTCsu/TmfahIDixKvr8cDa6F2WkBT8SOfv64W9PgiNv5B/BMOD2VWYaAl0N7yD0NkYYg/cDWRC4dfpdeip1jrr0k3mND0oSpIkxC+FicZbaYYwRdtJ9OSVWJ5OE0voLv8HgLze8mw6s4TrN3z+a2NQCveMa2VRN7YcEF7agPrvb/qU+otMwHae/wM7+f+HFAaOW+WTfzfxIVFB8/A1DN0NiEX+em4G7nO5F5ZcvfYPpaaioe8Nn33BbVLtMjXqsOBeM8AXiVfpD6YO75j7BqnBUPnivvD8BxJaaIQZvVSuQmvGm0ynt03IYwE8Rq+jYsunvsZ86jh5BiUR+Nm7sK0Qe9BdZn/7jdqohMv9czfMGUAscX+xBMunFbDpcRbWVpUADcm209L8Ndek2XY7YlCMxPgPVNvfWRF2jxehib9Tpd7zB5ZIDfAEH9zrpLfp29DLvCh2Yx8mH7xxdKG1O9Q0GdHphYHhej6smAcPm68R0GUQaTOLfXqNpueGJC1GAOI3Y4swjyt7jMTWcibnKLzwukWE5rnEDhn5n64JnyUM0ZFkRmtOiV";

static const char* output_path = "../output_files/";
static const char* input_path = "../input_files/fulltextsearch/";

void WriteUnicode(FILE* file, const wchar_t* text_content) {
  FS_WSTR str;
  FS_BSTR dst_bstr;

  str.str = (wchar_t*)text_content;
  str.len = wcslen(text_content);
  FSDK_WStr_UTF16LEEncode(&str, &dst_bstr);

  if (dst_bstr.len == 0) return;
  fwrite((const char*)dst_bstr.str, sizeof(char), dst_bstr.len, file);
}

FILE* file = NULL;

void gRelease(void* user_data) { 
  free(user_data); 
}

int gRetrieveSearchResult(void* user_data, const wchar_t* file_path, int page_index, const wchar_t* match_result, int match_start_text_index, int match_end_text_index, const wchar_t* sentence, int sentence_start_text_index, int sentence_end_text_index) {
  wchar_t result_str[1024] = { 0 };
  swprintf_s(result_str, 1024, L"RetrieveSearchResult:\nFound file is: %ls\nPage index is: %d\nStart text index: %d\nEnd text index: %d\nMatch is: %ls\nSentence start index:%d\nnSentence end index:%d\nSentence is:%ls\n", file_path, page_index, match_start_text_index, match_end_text_index, (const wchar_t*)match_result, sentence_start_text_index, sentence_end_text_index, (const wchar_t*)sentence);
  WriteUnicode(file, result_str);
  WriteUnicode(file, L"\r\n");

  return 0;
}

int pause_count_limit_ = 5;
int pause_count_ = 0;
FS_BOOL always_pause_ = TRUE;

FS_BOOL gNeedToPauseNow(void* user_data) {
  if (always_pause_) return TRUE;
  if (pause_count_ < pause_count_limit_) {
    pause_count_++;
    return TRUE;
  }
  if (pause_count_ < pause_count_limit_) {
    pause_count_++;
    return TRUE;
  } else {
     pause_count_ = 0;
     return FALSE; // This is to test a case: valid PauseCallback but needParseNow() will always return FALSE.
  }
}

int main(int argc, char *argv[]) {
  FSErrorCode error_code = e_FSErrSuccess;
  char output_directory[MAX_FILE_PATH];
  char output_file[MAX_FILE_PATH];
  char dbpath[MAX_FILE_PATH];

  sprintf_s(output_directory, MAX_FILE_PATH, "%sfulltextsearch/", output_path);
  _mkdir(output_directory);

  error_code = FSDK_Library_Initialize(sn, key);
  if (error_code != e_FSErrSuccess) {
    printf("Library Initialize Error: %d\n", error_code);
    return 1;
  }

  {
    FS_FULLTEXTSEARCH_HANDLE full_text_search = NULL;
    FS_DOCUMENTSSOURCE_HANDLE docs_source = NULL;
    FS_BOOL return_value;
    FS_PROGRESSIVE_HANDLE search_progress;
    FSPauseCallback* pausecallback = NULL;
    FSState state = e_FSToBeContinued;
    FSSearchCallback* search_callback = NULL;

    FSDK_FullTextSearch_Create(&full_text_search);
    //The path of data base to store the indexed data...
    sprintf_s(dbpath, MAX_FILE_PATH, "%ssearch.db", output_directory);
    FSDK_FullTextSearch_SetDataBasePath(full_text_search, dbpath);
    // Get document source information.

    FSDK_DocumentsSource_Create(input_path, &docs_source);
    // Create a Pause callback object implemented by users to pause the updating process.
    pausecallback = (FSPauseCallback*)malloc(sizeof(FSPauseCallback));
    pausecallback->user_data = pausecallback;
    pausecallback->NeedToPauseNow = gNeedToPauseNow;

    FSDK_FullTextSearch_StartUpdateIndex(full_text_search, docs_source, pausecallback, FALSE, &search_progress);

    while (state == e_FSToBeContinued) {
      FSDK_Progressive_Continue(search_progress, &state);
    }
    // Create a callback object which will be invoked when a matched one is found.
    search_callback = (FSSearchCallback*)malloc(sizeof(FSSearchCallback));
    search_callback->Release = gRelease;
    search_callback->user_data = search_callback;
    search_callback->RetrieveSearchResult = gRetrieveSearchResult;
    sprintf_s(output_file, MAX_FILE_PATH, "%sresult.txt", output_directory);
    fopen_s(&file, output_file, "w+b");
    // Search the specified keyword from the indexed data source.
    FSDK_FullTextSearch_SearchOf(full_text_search, "Foxit", e_FSRankHitCountASC, search_callback, &return_value);
    FSDK_FullTextSearch_Release(full_text_search);
    fclose(file);
    free(pausecallback);
    FSDK_Library_Release();
    printf("FullTextSearch demo.\n");
  }
  return 0;
}