// 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 to call layout recognition related classes
// for PDF document.


#include "FSPDFObjC.h"

NSString *input_path = @"../input_files/";
NSString *output_path = @"../output_files/";

NSString* sn = @"bPxThFlBAYifO3yiW0C51bKbjPap1zHaf5aG5sX378TjFvB7Q0802A==";
NSString* 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";

NSString *output_directory = [output_path stringByAppendingString:@"layout_recognition/"];

void getChildFromElement(FSLRStructureElement* pElement, NSMutableArray<FSLRElement *>* elemArray, FSLRElementElementType nType) {
    int nElemListSize = [pElement getChildCount];
    for (int i=0; i<nElemListSize; i++) {
        FSLRElement* item = [pElement getChild:i];
        FSLRElementElementType item_type = [item getElementType];
        if (item_type == nType) 
            [elemArray addObject:item];
        if ([item isStructureElement]) {
            FSLRStructureElement* srt_item = [[FSLRStructureElement alloc] initWithElement:item];
            getChildFromElement(srt_item, elemArray, nType);
        }
    }
}

void writeTextWithPrefix(NSFileHandle* doc, int depth, NSString* prefix, NSString* content) {
    for (int i = 0; i < depth; i++) {
        NSData* content_data = [prefix dataUsingEncoding:NSUTF8StringEncoding];
        [doc writeData:content_data];
    }
    NSData* content_data = [content dataUsingEncoding:NSUTF8StringEncoding];
    [doc writeData:content_data];
}

NSString* lr_Format(BOOL val) {
    return val ? @"True" : @"False";
}

NSString* lr_Format(int val) {
    return [NSString stringWithFormat:@"%d", val];
}

NSString* lr_Format(float val) {
    return [NSString stringWithFormat:@"%.1f", val];
}

NSString* lr_FormatARGB(long val) {
    return [NSString stringWithFormat:@"#%02X%02X%02X", (char)(val >> 16), (char)(val >> 8), (char)(val)];
}

NSString* lr_FormatAttributeValueEnum(FSLRStructureElementAttributeValueEnum val) {
    return [FSLRStructureElement stringifyEnumVariant:val];
}

void OutputLRStructureElement(FSLRStructureElement* element, NSFileHandle* doc, int depth) {
  if ([element isEmpty])
    return;

  FSLRStructureElement* parentElement = [element getParentElement];
  BOOL bIsEmpty = [parentElement isEmpty];

  FSLRElementElementType elemType = [element getElementType];
  NSString* elementTypeStr = [FSLRStructureElement stringifyElementType:elemType];
  NSString* outputStr = [NSString stringWithFormat:@"< StructureElement: %@ >\r\n", elementTypeStr];
  writeTextWithPrefix(doc, depth, @"\t", outputStr);

  int nSize = [element getSupportedAttributeCount];
  for (int i = 0; i < nSize; i++) {
    FSLRStructureElementAttributeType attrType = [element getSupportedAttribute:i];

    FSLRStructureElementAttributeValueType attrValueType = [element getAttributeValueType:attrType];
    int nLength = 0;
    BOOL bIsArray = [FSLRStructureElement isArrayAttributeValueType:attrValueType];
    nLength = [element getAttributeValueCount:attrType];
    if (attrValueType == FSLRStructureElementAttributeValueTypeEmpty)
      continue;

    NSString* szKey = [FSLRStructureElement stringifyAttributeType:attrType];
    NSString* szVal = @"";
    if (bIsArray)
      szVal = [szVal stringByAppendingString:@"["];

    for (int idx = 0; idx < nLength; idx++) {
      if (idx > 0)
        szVal = [szVal stringByAppendingString:@", "];

      switch (attrValueType) {
        case FSLRStructureElementAttributeValueTypeEnum:
        case FSLRStructureElementAttributeValueTypeEnumArray:
          szVal = [szVal
              stringByAppendingString:lr_FormatAttributeValueEnum([element getAttributeValueEnum:attrType index:idx])];
          break;
        case FSLRStructureElementAttributeValueTypeInt32:
        case FSLRStructureElementAttributeValueTypeInt32Array:
          szVal = [szVal stringByAppendingString:lr_Format([element getAttributeValueInt32:attrType index:idx])];
          break;
        case FSLRStructureElementAttributeValueTypeFloat:
        case FSLRStructureElementAttributeValueTypeFloatArray:
          szVal = [szVal stringByAppendingString:lr_Format([element getAttributeValueFloat:attrType index:idx])];
          break;
        case FSLRStructureElementAttributeValueTypeARGB:
        case FSLRStructureElementAttributeValueTypeARGBArray:
          szVal = [szVal stringByAppendingString:lr_FormatARGB([element getAttributeValueARGB:attrType index:idx])];
          break;
        case FSLRStructureElementAttributeValueTypeWStr:
        case FSLRStructureElementAttributeValueTypeWStrArray:
          szVal = [szVal stringByAppendingString:[element getAttributeValueString:attrType index:idx]];
          break;
      }
    }
    if (bIsArray)
      szVal = [szVal stringByAppendingString:@"]"];

    outputStr = [NSString stringWithFormat:@"%@: %@\r\n", szKey, szVal];
    writeTextWithPrefix(doc, depth, @"\t", outputStr);
  }
}

void OutputLRStructureElement(FSLRGraphicsObjectElement* element, NSFileHandle* doc, int depth) {
  if ([element isEmpty])
    return;

  NSString* outputStr = @"< LRGraphicsObjectElement: >\r\n";
  FSLRGraphicsObjectElement* parentPageObj = [element getParentGraphicsObjectElement];
  BOOL bIsEmpty = [parentPageObj isEmpty];
  writeTextWithPrefix(doc, depth, @"\t", outputStr);
  FSGraphicsObject* pageObj = [element getGraphicsObject];
  FSGraphicsObjectType type = 0;
  if (pageObj != nil)
    type = [pageObj getType];
  FSRectF* rcBox = [element getBBox];
  FSPDFDictionary* pDict = [element getDict];
  int objIndex = [element getGraphicsObjectIndex];
  FSMatrix2D* matrix = [element getMatrix];
  NSString* szVal = @"";
  szVal = [NSString stringWithFormat:@"BBox: [%.1f,%.1f,%.1f,%.1f]\r\n", [rcBox getLeft], [rcBox getTop], [rcBox getRight],
                            [rcBox getBottom]];
  writeTextWithPrefix(doc, depth, @"\t", szVal);
  szVal = [NSString stringWithFormat:@"Matrix: [%.1f,%.1f,%.1f,%.1f,%.1f,%.1f]\r\n", [matrix getA], [matrix getB], [matrix getC],
                            [matrix getD], [matrix getE], [matrix getF]];
  writeTextWithPrefix(doc, depth, @"\t", szVal);
  szVal = [NSString stringWithFormat:@"PageObjectIndex: %d\r\n", objIndex];
  writeTextWithPrefix(doc, depth, @"\t", szVal);

  NSString* text = (type == FSGraphicsObjectTypeText) ? [[pageObj getTextObject] getText] : @"";
  if ([text length] > 0) {
    szVal = [NSString stringWithFormat:@"Text: %@\r\n", text];
    writeTextWithPrefix(doc, depth, @"\t", szVal);
  }
}

void OutputLRStructureElement(FSLRContentElement* element, NSFileHandle* doc, int depth) {
  if ([element isEmpty])
    return;

  FSLRGraphicsObjectElement* pageObj = [element getGraphicsObjectElement];
  BOOL bIsEmpty = [pageObj isEmpty];
  FSLRStructureElement* parentPageObj = [element getParentElement];
  bIsEmpty = [parentPageObj isEmpty];

  FSLRElementElementType elemType = [element getElementType];
  NSString* elementTypeStr = [FSLRElement stringifyElementType:elemType];
  NSString* outputStr = [NSString stringWithFormat:@"< LRContentElement: %@ >\r\n", elementTypeStr];
  writeTextWithPrefix(doc, depth, @"\t", outputStr);

  FSRectF* rcBox = [element getBBox];
  int nStartPos = 0, nLength = 0;
  FSRange* range = [element getGraphicsObjectRange];
  if (![range isEmpty]) {
    nStartPos = [range getSegmentStart:0];
    nLength = [range getSegmentEnd:0] - nStartPos + 1;
  }
  FSMatrix2D* matrix = [element getMatrix];

  NSString* szVal = @"";
  szVal = [NSString stringWithFormat:@"BBox: [%.1f,%.1f,%.1f,%.1f]\r\n", [rcBox getLeft], [rcBox getTop], [rcBox getRight],
                            [rcBox getBottom]];
  writeTextWithPrefix(doc, depth, @"\t", szVal);
  szVal = [NSString stringWithFormat:@"Matrix: [%.1f,%.1f,%.1f,%.1f,%.1f,%.1f]\r\n", [matrix getA], [matrix getB], [matrix getC],
                            [matrix getD], [matrix getE], [matrix getF]];
  writeTextWithPrefix(doc, depth, @"\t", szVal);
  szVal = [NSString stringWithFormat:@"StartPos: %d\r\n", nStartPos];
  writeTextWithPrefix(doc, depth, @"\t", szVal);
  szVal = [NSString stringWithFormat:@"Length: %d\r\n", nLength];
  writeTextWithPrefix(doc, depth, @"\t", szVal);

  if (!bIsEmpty)
    OutputLRStructureElement(pageObj, doc, depth + 1);
}

void showLRElementInfo(FSLRStructureElement* element, NSFileHandle* doc, int depth) {
  int nElemListSize = [element getChildCount];
  OutputLRStructureElement(element, doc, depth);
  for (int i = 0; i < nElemListSize; i++) {
    FSLRElement* item = [element getChild:i];
    FSLRElementElementType item_type = [item getElementType];
    if ([item isStructureElement]) {
      FSLRStructureElement* srt_item = [[FSLRStructureElement alloc] initWithElement:item];
      showLRElementInfo(srt_item, doc, depth + 1);
    } else if ([item isContentElement]) {
      FSLRContentElement* srt_item = [[FSLRContentElement alloc] initWithElement:item];
      OutputLRStructureElement(srt_item, doc, depth);
    } else if ([item isGraphicsObjectElement]) {
      FSLRGraphicsObjectElement* srt_item = [[FSLRGraphicsObjectElement alloc] initWithElement:item];
      OutputLRStructureElement(srt_item, doc, depth);
    }
  }
}

void outputAllLRElement(FSLRStructureElement* element, NSString* info_path) {
  NSFileManager* file_manager = [NSFileManager defaultManager];
  if (![file_manager createFileAtPath:info_path contents:nil attributes:nil]) {
    NSLog(@"Fail to create txt file %@\r\n", info_path);
    return;
  }
  NSFileHandle* text_doc = [NSFileHandle fileHandleForWritingAtPath:info_path];
  if (![element isEmpty]) {
    showLRElementInfo(element, text_doc, 0);
  } else {
    NSString* record_content = @"No layout recognition information!\r\n";
    NSData* content_data = [record_content dataUsingEncoding:NSUTF8StringEncoding];
    [text_doc writeData:content_data];
  }
  [text_doc closeFile];
}

int main(int argc, const char * argv[]) {
	bool is_run_success = false;
	@autoreleasepool {
        
        NSFileManager *fileManager = [NSFileManager defaultManager];
		BOOL isDir = NO;
		if ([fileManager fileExistsAtPath:output_directory isDirectory:&isDir]) {
			if (!isDir) {
				NSError *error = nil;
				if (![fileManager removeItemAtPath:output_directory error:&error] || error) {
					return -1;
				}
				if (![fileManager createDirectoryAtPath:output_directory withIntermediateDirectories:YES attributes:nil error:&error] || error) {
					return -1;
				}
			}
		} else {
			NSError *error = nil;
			if (![fileManager createDirectoryAtPath:output_directory withIntermediateDirectories:YES attributes:nil error:&error] || error) {
				return -1;
			}
		}
    
		// Initialize library
		FSErrorCode errorCode = [FSLibrary initialize:sn key:key];
		if (errorCode != FSErrSuccess) {
			NSLog(@"Library Initialize Error: %ld", errorCode);
			return -1;
		}
		
		@try {
            NSString* input_file = [input_path stringByAppendingPathComponent:@"AboutFoxit.pdf"];
            NSString* info_file = [output_directory stringByAppendingPathComponent:@"layout_recognition_info.txt"];
            FSPDFDoc* doc = [[FSPDFDoc alloc] initWithPath:input_file];
            FSErrorCode errorCode = [doc load:nil];
            if (errorCode != FSErrSuccess) {
                NSLog(@"The Doc [%@] Error: %ld", input_file, errorCode);
                return -1;
            }
            
            FSPDFPage* original_page = [doc getPage:0];
            [original_page startParse:FSPDFPageParsePageNormal pause:nil is_reparse:false];
            FSLRContext* context = [[FSLRContext alloc] initWithPage:original_page];

            FSProgressive* progressive = [context startParse:nil];

            FSLRStructureElement* root = [context getRootElement];
            FSLRElementElementType type = [root getElementType];
            int nElemListSize = [root getChildCount];
            NSLog(@"RootElement getChildCount: %d", nElemListSize);
            outputAllLRElement(root, info_file);

            NSMutableArray<FSLRElement*>* element_array = [NSMutableArray arrayWithCapacity:10];
            getChildFromElement(root, element_array, FSLRElementElementTypeSpan);
            NSLog(@"LRElement::e_ElementTypeSpan count: %ld\n", element_array.count);

            NSLog(@"Layout recognition test.");
            is_run_success = true;
		}
		@catch (NSException *e) {
			NSLog(@"Unknown Exception, %@", e);
		}
	}
	[FSLibrary destroy];
  return is_run_success ? 0 : 1;
}

