// 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 save a PDF document as a wrapper file
// and then open the wrapper file.

//#include <vector>
//#include <cstdio>
#include "FSPDFObjC.h"

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

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";

void RenderPDF2Img(FSPDFDoc *doc) {
	int page_count = [doc getPageCount];
	
	for (int i = 0; i < page_count; i++) {
		FSPDFPage *page = [doc getPage:i];
		
		// Parse page.
		[page startParse:FSPDFPageParsePageNormal pause:nil is_reparse:NO];
		
		int width = static_cast<int>([page getWidth]);
		int height = static_cast<int>([page getHeight]);
		FSMatrix2D *matrix = [page getDisplayMatrix:0 top:0 width:width height:height rotate:[page getRotation]];
		
		// Prepare a bitmap for rendering.
		FSBitmap *bitmap = [[FSBitmap alloc] initWithWidth:width height:height format:FSBitmapDIBArgb buffer:nil pitch:0];
		[bitmap fillRect:0xFFFFFFFF rect:nil];
		
		// Render page
		FSRenderer *renderer = [[FSRenderer alloc] initWithBitmap:bitmap is_rgb_order:NO];
		[renderer startRender:page matrix:matrix pause:nil];
		// Add the bitmap to an image and save the image.
		FSImage *image = [[FSImage alloc] init];
		[image addFrame:bitmap];
		NSString *image_name = [NSString stringWithFormat:@"AboutFoxit_%d_wrapper.jpg", i];
		image_name = [output_directory stringByAppendingPathComponent:image_name];
		if (![image saveAs:image_name]) {
			printf("[Failed] Cannot save image file.\r\nPage index: %d", i);
		}
	}
}

namespace {
	typedef long long int		int64;
	typedef unsigned long long	FILESIZE;
	class FileReader
	{
	public:
		FileReader(int64 offset) : file_(NULL)
		, filesize_(offset) {}
		~FileReader() {}
		
		bool LoadFile(const char* file_path) {
			file_ = fopen(file_path, "rb");
			if (!file_) return FALSE;
			return TRUE;
		}
		
		FILESIZE  GetSize()
		{
			return filesize_;
		}
		
		int ReadBlock(void* buffer, FILESIZE offset, size_t size)
		{
			if (!file_) return 0;
			if(0 != fseek(file_, (long)offset, 0))
				return 0;
			if(0 == fread(buffer, size, 1, file_))
				return 0;
			return 1;
		}
		
		size_t ReadBlock(void* buffer, size_t size) {
			if (!file_) return false;
			if(0 != fseek(file_, 0, 0))
				return 0;
			return fread(buffer, size, 1, file_);
		}
		
		void Release() {
			if(file_)
				fclose(file_);
			file_ = NULL;
		}
		
	private:
		FILE* file_;
		int64 filesize_;
	};
}

@interface FSFileRead : NSObject<FSFileReaderCallback>

- (id)initWithSourceFilePath:(NSString *)path offset:(long long)offset;

@end

@implementation FSFileRead {
	FileReader *imp;
}

- (id)initWithSourceFilePath:(NSString *)path offset:(long long)offset {
	if (self = [super init]) {
		//"offset" can also indicate the end position of the document or the document size
		imp = new FileReader(offset);
		if (!imp->LoadFile([path UTF8String])) {
			NSLog(@"failed to load source file %@", path);
			return nil;
		}
	}
	return self;
}

- (void)dealloc {
	delete imp;
}

- (unsigned long long)getSize {
	return imp->GetSize();
}

- (NSData *)readBlock:(unsigned long long)offset size:(unsigned long long)size {
	void *buffer = malloc(size);
	if (!buffer) {
		NSLog(@"failed to malloc buffer of size %llu", size);
		return nil;
	}
	if (imp->ReadBlock(buffer, offset, (size_t)size)) {
		return [NSData dataWithBytesNoCopy:buffer length:size];
	} else {
		NSLog(@"failed to read block");
		free(buffer);
		return nil;
	}
}

@end

@interface FSFileWriterCallbackImpl : NSObject<FSFileWriterCallback>
@property (nonatomic) FILE* mfile;
@property (nonatomic, strong) NSString* filePath;
-(BOOL)LoadFile:(NSString *)filePath;
@end

@implementation FSFileWriterCallbackImpl
-(BOOL)LoadFile:(NSString *)filePath
{
	self.filePath = filePath;
	const char* mfilePath = [filePath cStringUsingEncoding:NSUTF8StringEncoding];
	self.mfile = fopen(mfilePath, "wb");
	if (!self.mfile) return NO;
	return TRUE;
}

-(unsigned long long)getSize {
	if (!self.mfile) return NO;
	
	fseek(self.mfile, 0, SEEK_END);
	return (uint32)ftell(self.mfile);
}

-(BOOL)writeBlock:(NSData*)data offset:(unsigned long long)offset {
	if (!self.mfile) return NO;
	
	NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:self.filePath];
	[fileHandle seekToEndOfFile];
	[fileHandle writeData:data];
	[fileHandle closeFile];
	
	return YES;
}

-(BOOL)flush {
	return YES;
}
@end

bool OpenWrapperFile(NSString *file_name) {
	NSMutableString *file_info = @"".mutableCopy;
	FSPDFDoc *doc = [[FSPDFDoc alloc] initWithPath:file_name];
	FSErrorCode code = [doc load:nil];
	if (code != FSErrSuccess) {
		NSLog(@"The Doc [%@] Error: %d", file_name, (int)code);
		return false;
	}
	if (![doc isWrapper]) {
		NSLog(@"[Failed] %@ is not a wrapper file.", file_name);
		return false;
	}
	long long offset = [doc getWrapperOffset];
	[file_info appendFormat:@"offset: %lld\n", offset];
	FSWrapperData *wrapper_data = [doc getWrapperData];
	[file_info appendFormat:@"version: %d\n", [wrapper_data getVersion]];
	[file_info appendFormat:@"type: %@\n", [wrapper_data getType]];
	[file_info appendFormat:@"app_id: %@\n", [wrapper_data getApp_id]];
	[file_info appendFormat:@"uri: %@\n", [wrapper_data getUri]];
	[file_info appendFormat:@"description: %@\n", [wrapper_data getDescription]];

	NSString *file_info_path = [output_directory stringByAppendingPathComponent:@"Wrapperinfo.txt"];
	[[file_info dataUsingEncoding:NSUTF8StringEncoding] writeToFile:file_info_path atomically:YES];

	FSFileRead *file_reader = [[FSFileRead alloc] initWithSourceFilePath:file_name offset:offset];

	FSPDFDoc *doc_real = [[FSPDFDoc alloc] initWithFile_read:file_reader is_async:NO];
	code = [doc_real load:nil];
	if (code != FSErrSuccess) {
		NSLog(@"[Failed] Cannot load real PDF document.\nError Message: %d", (int)code);
		return false;
	}
	RenderPDF2Img(doc_real);
	return true;
}

int main(int argc, const char * argv[]) {
	
	@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;
		}
		
		NSString *input_file = [input_path stringByAppendingPathComponent:@"wrapper.pdf"];
		
		@try {
			// Load PDF document.
			FSPDFDoc *doc_wrapper = [[FSPDFDoc alloc] initWithPath:input_file];
			FSErrorCode code = [doc_wrapper load:nil];
			if (code != FSErrSuccess) {
				NSLog(@"[Failed] Cannot load PDF document: %@.\nError Code: %d", input_file, (int)code);
				return 1;
			}
			// Save the PDF document as a wrapper file.
			FSWrapperData *wrapperData = [[FSWrapperData alloc] initWithVersion:10 type:@"Foxit" app_id:@"Foxit" uri:@"www.foxitsoftware.com" description:@"Foxit"];
			
			NSString *output_file = [output_directory stringByAppendingPathComponent:@"AboutFoxit_wrapper.pdf"];
			
			FSPDFDoc *doc_real = [[FSPDFDoc alloc] initWithPath:[input_path stringByAppendingPathComponent:@"AboutFoxit.pdf"]];
			code = [doc_real load:nil];
			if (code != FSErrSuccess) {
				NSLog(@"[Failed] Cannot load PDF document: %@.\nError Code: %d", [input_path stringByAppendingPathComponent:@"AboutFoxit.pdf"], (int)code);
				return 1;
			}
			[doc_real saveAs:output_file save_flags:FSPDFDocSaveFlagNormal];
			
			// "0xFFFFFFFC" can be changed to other values defined in enumeration FSUserPermissions.
			[doc_wrapper saveAsWrapperFile:output_file wrapper_data:wrapperData user_permissions:0xFFFFFFFC owner_password:nil];
			
			// Open the wrapper file.
			if (!OpenWrapperFile(output_file)) {
				return 1;
			}
			
			printf("Add wrapper to PDF file.\n");
			
			output_file = [output_directory stringByAppendingPathComponent:@"AboutFoxit_payloadfile.pdf"];
			[doc_wrapper startSaveAsPayloadFile:output_file payload_file_path:[input_path stringByAppendingPathComponent:@"AboutFoxit.pdf"] crypto_filter:@"Unknown" description:@"no_description" version:1.0 save_flags:FSPDFDocSaveFlagIncremental pause:nil];
			
			printf("Save as payload file.\n");
			
			input_file = [input_path stringByAppendingPathComponent:@"Microsoft IRM protection 2.pdf"];
			FSPDFDoc *doc_rmsv2 = [[FSPDFDoc alloc] initWithPath:input_file];
			code = [doc_rmsv2 load:nil];
			if (code != FSErrSuccess) {
				NSLog(@"[Failed] Cannot load PDF document: %@.\nError Code: %d", input_file, (int)code);
				return 1;
			}
			
			output_file = [output_directory stringByAppendingPathComponent:@"MicrosoftIRMServices Protected PDF.pdf"];
			FSPDFDocWrapperType wrappertype = [doc_rmsv2 getWrapperType]; 
			if (wrappertype == FSPDFDocWrapperPDFV2) {
				FSFileWriterCallbackImpl *filewriter = [[FSFileWriterCallbackImpl alloc] init];
				[filewriter LoadFile:output_file];
				[doc_rmsv2 startGetPayloadFile:filewriter pause:nil];
				printf("Get RMS V2 PDF file.\n");
			}
		}
		@catch (NSException *e) {
			NSLog(@"Unknown Exception, %@", e);
			return -1;
		}
	}
	[FSLibrary destroy];
	return 0;
}
