// 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 get preflight keys and analyze or fixup PDF file.

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

@interface MyComplianceProgressCallback : NSObject<FSComplianceProgressCallback>
{
		@private
		NSMutableString* output_data_;
}
-(id)init;
-(void)saveProgressDataToFile:(NSString*)output_file_path;
@end

@implementation MyComplianceProgressCallback

-(id)init {
	output_data_ = [NSMutableString new];
	return self;
}

-(void)updateCurrentStateData: (int)current_rate current_state_string: (NSString*)current_state_string {
	NSLog(@"Current rate: %d", current_rate);
	
	[output_data_ appendString:[NSString stringWithFormat:@"Current rate:%d, state str:", current_rate]];
	[output_data_ appendString:current_state_string];
	[output_data_ appendString:@"\r\n"];
}

-(void)saveProgressDataToFile:(NSString*)output_file_path {
	[[output_data_ dataUsingEncoding:NSUTF8StringEncoding] writeToFile:output_file_path atomically:YES];
}
@end

void ListPreflightKeys(FSPreflight* preflight, FSPreflightSettingDataLibraryType library_type, FSPreflightSettingDataOperateType operate_type) {
  NSArray<NSData *> *group_arr = [preflight getGroupNamesArray:library_type operate_type:operate_type];
  for (int i = 0; i < [group_arr count]; i++){
    NSData *data = group_arr[i];
    NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"Group name: %@",string);
    NSArray<NSData *> * item_array = [preflight getItemKeysArray:string];
    
    NSLog(@"    Item count: %lu",[item_array count]);
    for (int j = 0; j < [item_array count];j++){
        NSData *data1 = item_array[j];
        string = [[NSString alloc] initWithData:data1 encoding:NSUTF8StringEncoding];
        NSLog(@"    Item name: %@",string);
    }
  }
}

void AnalyzeAndFixup(FSPreflight* preflight, FSPreflightSettingDataOperateType operate_type, NSString *preflight_key, bool is_fixed) {
    FSPreflightSettingData* setting_data = [FSPreflightSettingData new];
    setting_data.operate_type = operate_type;
    setting_data.preflight_key = preflight_key;
    setting_data.first_page_index = 0;
    setting_data.src_pdf_path = [input_path stringByAppendingString:@"AboutFoxit.pdf"];
    NSString *output_directory = [output_path stringByAppendingString:@"preflight/"];
    NSString *fixpath = [NSString stringWithFormat:@"%@AboutFoxit_%@_fixed.pdf", output_directory, preflight_key];
    setting_data.saved_pdf_path = fixpath;
    MyComplianceProgressCallback* verify_progress_callback = [[MyComplianceProgressCallback alloc] init];
    NSString *progressdata_output_file = [NSString stringWithFormat:@"%@AboutFoxit_%@_progress.txt", output_directory, preflight_key];
    [verify_progress_callback saveProgressDataToFile:progressdata_output_file];
    if (is_fixed)
        [preflight analyzeAndFixup:setting_data progress_callback:verify_progress_callback];
    else
        [preflight analyze:setting_data  progress_callback:verify_progress_callback];
    [verify_progress_callback saveProgressDataToFile:progressdata_output_file];}

void GenerateReport(FSPreflight* preflight, FSPreflightReportSettingDataReportFileFormatType format_type, NSString *preflight_key) {
	FSPreflightReportSettingData* report_setting_data = [FSPreflightReportSettingData new];
	report_setting_data.report_file_format_type = format_type;
	NSString *output_directory = [output_path stringByAppendingString:@"preflight/"];
	NSString *path = [NSString stringWithFormat:@"%@AboutFoxit_%@_report.pdf", output_directory, preflight_key];
	report_setting_data.report_file_path = path;
	report_setting_data.to_generate_overview = true;
	report_setting_data.to_highlight_problems = true;
	report_setting_data.problems_highlight_method = FSPreflightReportSettingDataProblemsHighlightMethodTransparentMasks;
    [preflight generateReport:report_setting_data progress_callback:nil];
}

int main(int argc, const char * argv[]) {
	
	@autoreleasepool {
		NSString *output_directory = [output_path stringByAppendingString:@"preflight/"];
		
		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:@"AboutFoxit.pdf"];
		
		@try {
			// "compliance_resource_folder_path" is the path of compliance resource folder. Please refer to Developer Guide for more details.
			NSString* compliance_resource_folder_path = @"";
			// If you use an authorization key for Foxit PDF SDK, please set a valid unlock code string to compliance_engine_unlockcode for FSComplianceEngine.
			// If you use an trial key for Foxit PDF SDK, just keep compliance_engine_unlockcode as an empty string.
			NSString* compliance_engine_unlockcode = @"";
			
			if ([compliance_resource_folder_path length] < 1) {
				NSLog(@"compliance_resource_folder_path is still empty. Please set it with a valid path to compliance resource folder path.");
				return -1;
			}
			// Initialize compliance engine.
			errorCode = [FSComplianceEngine initialize:compliance_resource_folder_path compliance_engine_unlockcode:compliance_engine_unlockcode];
			if (errorCode != FSErrSuccess) {
				switch (errorCode) {
					case FSErrInvalidLicense:
						NSLog(@"[Failed] Compliance module is not contained in current Foxit PDF SDK keys.\n");
						break;
					default:
						NSLog(@"[Failed] Fail to initialize compliance engine. Error: %ld", errorCode);
						break;
				}
				return -1;
			}
			NSLog(@"FSComplianceEngine is initialized.");

			{
				FSPreflight *preflight = [[FSPreflight alloc] init];
				// List all Foxit preflight keys.
				NSLog(@"Library Type: Foxit, Operate Type: Profiles");
				ListPreflightKeys(preflight, FSPreflightSettingDataLibraryTypeFoxit, FSPreflightSettingDataOperateTypeProfiles);
				NSLog(@"Library Type: Foxit, Operate Type: Checks");
				ListPreflightKeys(preflight, FSPreflightSettingDataLibraryTypeFoxit, FSPreflightSettingDataOperateTypeSingleChecks);
				NSLog(@"Library Type: Foxit, Operate Type: Fixups");
				ListPreflightKeys(preflight, FSPreflightSettingDataLibraryTypeFoxit, FSPreflightSettingDataOperateTypeSingleFixups);
				
				BOOL isFixup = NO;
				// Analyze and fixup a PDF file.
				NSLog(@"== Profiles. ==");
				isFixup = [preflight canFixup:@"pppp_ConverttoPDFA1a"];
				AnalyzeAndFixup(preflight, FSPreflightSettingDataOperateTypeProfiles, @"pppp_ConverttoPDFA1a", isFixup);
				GenerateReport(preflight, FSPreflightReportSettingDataReportFileFormatTypePdf, @"pppp_ConverttoPDFA1a");

				//Analyze a PDF file.
				NSLog(@"== Single Checks. ==");
				AnalyzeAndFixup(preflight, FSPreflightSettingDataOperateTypeSingleChecks, @"R_6_Annotationinsidepagearea" ,NO);
				GenerateReport(preflight, FSPreflightReportSettingDataReportFileFormatTypePdf, @"R_6_Annotationinsidepagearea");
				
				//Fixup a PDF file.
				NSLog(@"== Single Fixups. ==");
				AnalyzeAndFixup(preflight, FSPreflightSettingDataOperateTypeSingleFixups,@"F_9_RemoveXMPMetadataifnotcompliantwithPDFA1",YES);
				GenerateReport(preflight, FSPreflightReportSettingDataReportFileFormatTypePdf, @"F_9_RemoveXMPMetadataifnotcompliantwithPDFA1");
			}


			// Release compliance engine.
			[FSComplianceEngine destroy];
			
			NSLog(@"== End: Preflight demo. ==");
		}
		@catch (NSException *e) {
			NSLog(@"Unknown Exception, %@", e);
			return -1;
		}
	}
	[FSLibrary destroy];
	return 0;
}
