package com.digertech.sdk.samples;

import java.io.File;
import java.io.RandomAccessFile;

import com.digertech.sdk.imgvalidate.IVLicenseInfo;
import com.digertech.sdk.imgvalidate.ImageException;
import com.digertech.sdk.imgvalidate.ImageTagValue;
import com.digertech.sdk.imgvalidate.ImageValidator;

/**
* This sample load the image data from the file and validate 
* the image data according to X9.100-181 standard and print 
* image validation results.
* 
* To run this sample, a jar file in the lib folder should 
* be included in the classpath:
*   ImageValidationSDK.jar
*   
* Execute the commmand to run the sample : 
*  java com.digertech.sdk.samples.SampleImageValidator [TIFF image file] [license key]
*           [TIFF image file] - TIFF image file full path name.
*           [license key]     - Image Validation SDK license key.
*/ 
public class SampleImageValidator {
	
	public SampleImageValidator() {
		super();
	}

	public static void setLicenseKey() {
		// The license key contains 25 chars. You will recieve the license key after you
		// purchase the SDK product.
		String validateLicenseKey = "YYYYYYYYYYYYYYYYYYYYYYYYY";

		setLicenseKey(validateLicenseKey);
	}
	public static void setLicenseKey(String validateLicenseKey) {
		System.out.println("****************************************************");
		System.out.println("*  DigerTech Inc. ICL Image Validation SDK Sample  *");
		System.out.println("*                                                  *");
		System.out.println("*               Version : " + IVLicenseInfo.VERSION + "                    *");
		System.out.println("****************************************************");
		System.out.println("                                                    ");

		// Make sure the license key is set to the SDK before it starts to process files
		// or validate the images. Set the license key only one time when the JVM starts.
		
		// If the license key is valid, SDK will return the valid product id of the license.
		// othwise the productId is free version
		int productId = ImageValidator.setLicenseKey(validateLicenseKey);
		
		if (productId == ImageValidator.SDK_IMAGE_VALIDATE_DEVELOPER) {
			System.out.println("This is a Developer version SDK license. SDK can check or validate less than 1000 images.");
		} else if (productId == ImageValidator.SDK_IMAGE_VALIDATE_ENTERPRISE_I) {
			System.out.println("This is an Enterprise I version SDK license. SDK can only check unlimited images.");
		} else if (productId == ImageValidator.SDK_IMAGE_VALIDATE_ENTERPRISE_II) {
			System.out.println("This is an Enterprise II version SDK license. SDK can check or validate unlimited images.");
 		} else {
			System.out.println("This is a free version SDK license. SDK can check or validate less than 20 images.");
		}
		
		IVLicenseInfo ivLicenseInfo = ImageValidator.getLicenseInfo();
		System.out.println("------------------------- ");
		System.out.println("Computer Id             = " + ivLicenseInfo.getComputerId());
		System.out.println("Product Id              = " + ivLicenseInfo.getProductId());
		System.out.println("Version                 = " + ivLicenseInfo.getVersion());
		System.out.println("Permanent               = " + ivLicenseInfo.isPermanent());
		System.out.println("Expired                 = " + ivLicenseInfo.isExpired());
		System.out.println("Maintiance Expired Date = " + ivLicenseInfo.getMaintainanceDate());
		System.out.println("------------------------- ");
	}
	
	private void validateImage(byte[] imageData) {
		ImageValidator  imgValidator = new ImageValidator();

		System.out.println("                                ");
		System.out.println("====== Validate Image Data =====");

		try {
			if (imgValidator.isImageValid(imageData)) {
				System.out.println(" Image is valid. ");
			} else {
				System.out.println(" Image is invalid. ");
			}	

			// return all tags in the image.
			int tags[] = imgValidator.validateImage(imageData);
			
			// print all the image properties. all these properties are only available after
			// validateImage(imageData) method is called.
			System.out.println("EOFB            = " + imgValidator.isEOFB());
			System.out.println("LittleEndian    = " + imgValidator.isLittleEndian());
			System.out.println("SinglePage      = " + imgValidator.isSinglePage());
			System.out.println("TagInOrder      = " + imgValidator.isTagInOrder());
			
			for (int i=0;i<tags.length;i++) {
				ImageTagValue tagValue = imgValidator.getTagValue(tags[i]);
				System.out.println("tag            = " + tagValue.getTagNum());
				System.out.println("type           = " + tagValue.getType());
				System.out.println("offset         = " + tagValue.getOffset());
				System.out.println("count          = " + tagValue.getCount());
				System.out.println("value          = " + tagValue.getValue());
				System.out.println("valid code     = " + tagValue.getValidCode());
				System.out.println("valid          = " + tagValue.isValid());
				
				if (!tagValue.isValid()) {
					System.out.println("   Fail On Byte Order   = " + tagValue.isFailOnByteOrder());
					System.out.println("   Fail On Byte Size    = " + tagValue.isFailOnByteSize());
					System.out.println("   Fail On Count        = " + tagValue.isFailOnCount());
					System.out.println("   Fail On Tag Order    = " + tagValue.isFailOnTagOrder());
					System.out.println("   Fail On Type         = " + tagValue.isFailOnType());
					System.out.println("   Fail On Value        = " + tagValue.isFailOnValue());
					System.out.println("   Fail On Value Offset = " + tagValue.isFailOnValueOffset());
				}
				
				System.out.println("----------------------");
			}
		} catch (ImageException e) {
			System.out.println("Error validate image. " + e.toString());
		}
		System.out.println("                                ");
	}
	
	public static void main(String args[]) {
		if (args == null || args.length < 1) {
			System.out.println(new StringBuffer().append("Usage:  \n") 
				  .append("java SampleImageValidator [TIFF image file] [license key]\n")
				  .append("              [TIFF image file] - TIFF image file full path name.\n")
				  .append("              [license key]     - Image Validation SDK license key.\n")
				  .toString());
		} else {
			// Set the SDK license key before we process any files.
			// If it is better to set SDK license key when the JVM starts.
			if (args.length == 2) {
				setLicenseKey(args[1]);
			} else {
				setLicenseKey();
			}
			
			File                 file      = new File(args[0]);
			RandomAccessFile     raf       = null;
			SampleImageValidator validator = null;
			
			try {
				byte[] imageData = new byte[(int)file.length()];
		
				// Initialize this sample file which implements the ProcessingInterface
				validator = new SampleImageValidator();
				
				// load the image data from the file.
				raf = new RandomAccessFile(file, "r");
				raf.read(imageData);

				// validate the image data.
				validator.validateImage(imageData);
			} catch (Exception e) {
				System.out.println("Error validating image file. " + e.toString());
			} finally {
				if (raf != null) {
					// ensure to close the image file after the file is processed.
					try {
						raf.close();
					} catch (Exception e) {
						System.out.println("Error closing image file. " + e.toString());
					}
				}
			}
			
		}
	}

}
