//
//  POSSDKViewController.m
//  POSSDKFORIOS2013
//
//  Created by liangchenying on 12-4-6.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "POSSDKViewController.h"
#import "Text.h"
#import "Barcode.h"
#import "PDF417.h"
#import "GS1DataBar.h"
#import "standardMode.h"
#import "RasterImage.h"
#import "Image.h"
#import "barcodeQR.h"
#import "RAMorFlashImage.h"
#import "TextRasterprint.h"
#import "TestController.h"

#import "ButtonPullDownPrepare.h"
#import "ButtonPullDownRealize.h"

#import <CoreBluetooth/CoreBluetooth.h>

@interface POSSDKViewController()
{
    PortType selectedPortType;
    NSMutableArray	*port_info_set;
}

@property (nonatomic, retain) POSSDK	    *pos_sdk;
@property (nonatomic, retain) PortIO	    *printer_port;

@end

@implementation POSSDKViewController

@synthesize BarcodePrint               = _BarcodePrint;
@synthesize PDF417Print                = _PDF417Print;
@synthesize IPAddr                     = _IPAddr;
@synthesize MaxicodePrint              = _MaxicodePrint;
@synthesize GS1DataBarPrint            = _GS1DataBarPrint;
@synthesize standardModePrint          = _standardModePrint;
@synthesize pageModePrint              = _pageModePrint;
@synthesize RasterImageprint           = _RasterImageprint;
@synthesize ImagePrint                 = _ImagePrint;
@synthesize QRPrint                    = _QRPrint;
@synthesize SearchPrinterButton        = _SearchPrinterButton;
@synthesize ImageRAMorFlash            = _ImageRAMorFlash;
@synthesize TextRasterPrintButton      = _TextRasterPrintButton;
@synthesize UserDefinedCharacterButton = _UserDefinedCharacterButton;
@synthesize DownloadFileButton         = _DownloadFileButton;

@synthesize ConnectPrinter             = _ConnectPrinter;
@synthesize TextPrint                  = _TextPrint;
@synthesize pos_sdk                    = _pos_sdk;
@synthesize printer_port               = _printer_port;
@synthesize array_SearchPrinter	       = _array_SearchPrinter;
@synthesize selectedSearchPrinter      = _selectedSearchPrinter;

@synthesize array_DeviceList	       = _array_DeviceList;
@synthesize selectedBlueToothDevice    = _selectedBlueToothDevice;
@synthesize selectedPortType           = _selectedPortType;

- (POSSDK*)pos_sdk
{
	if(_pos_sdk == nil)
	{
		_pos_sdk = [[POSSDK alloc] init];
	}
	return _pos_sdk;
}

- (PortIO*)printer_port
{
	if(_printer_port == nil)
	{
        if(selectedPortType == PORT_TYPE_WIFI){
            _printer_port = [[WIFIPort alloc] init:false];
        }else if(selectedPortType == PORT_TYPE_BluetoothBLE){
            _printer_port = [[BlueToothPort alloc] init];
        }else{
            _printer_port = [[BluetoothMFI alloc] init];
        }
	}
	return _printer_port;
}

- (NSMutableArray*)array_SearchPrinter
{
    if(_array_SearchPrinter  == nil)
    {
        _array_SearchPrinter = [[NSMutableArray alloc] initWithCapacity:1024];
    }
    
    return _array_SearchPrinter;
}

- (NSMutableArray*)array_DeviceList
{
    if(_array_DeviceList  == nil)
    {
        _array_DeviceList = [[NSMutableArray alloc] initWithCapacity:1024];
    }
    
    return _array_DeviceList;
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
	[super viewDidLoad];
	
    [self setPos_sdk:nil];
	[self setPrinter_port:nil];
	[self.ConnectPrinter setTitle:@"Connect" forState:UIControlStateNormal];
	
    [self.IPAddr  setDelegate:self];
    [self.IPAddr  setText:@""];
	
    ButtonEnableAndAlpha(self.TextPrint, 0, 0);
    ButtonEnableAndAlpha(self.BarcodePrint, 0, 0);
    ButtonEnableAndAlpha(self.PDF417Print, 0, 0);
    ButtonEnableAndAlpha(self.MaxicodePrint, 0, 0);
    ButtonEnableAndAlpha(self.GS1DataBarPrint, 0, 0);
    ButtonEnableAndAlpha(self.standardModePrint, 0, 0);
    ButtonEnableAndAlpha(self.pageModePrint, 0, 0);
    ButtonEnableAndAlpha(self.RasterImageprint, 0, 0);
    ButtonEnableAndAlpha(self.ImagePrint, 0, 0);
    ButtonEnableAndAlpha(self.QRPrint, 0, 0);
    ButtonEnableAndAlpha(self.ImageRAMorFlash, 0, 0);
    ButtonEnableAndAlpha(self.TextRasterPrintButton, 0, 0);
    ButtonEnableAndAlpha(self.UserDefinedCharacterButton, 0, 0);
    ButtonEnableAndAlpha(self.DownloadFileButton, 0, 0);
	ButtonEnableAndAlpha(self.SearchPrinterButton, 1, 1);
	ButtonEnableAndAlpha(self.IPAddr, 1, 1);
	ButtonEnableAndAlpha(self.ConnectPrinter, 1, 1);
    ButtonEnableAndAlpha(self.ToCustomButton, 0, 0);
    
    selectedPortType = PORT_TYPE_WIFI;
    [self.selectPortTypeSegmented addTarget:self action:@selector(didClickPortTypeSegmentedControlAction:) forControlEvents:UIControlEventValueChanged];
}

-(void)didClickPortTypeSegmentedControlAction:(UISegmentedControl *)Seg{
    NSInteger index = Seg.selectedSegmentIndex;
    
    switch(index){
        case 0: //WIFI
            selectedPortType = PORT_TYPE_WIFI;
            break;
            
        case 1: //Bluetooth(BLE)
            selectedPortType = PORT_TYPE_BluetoothBLE;
            break;
            
        case 2: //Bluetooth(MFI)
            selectedPortType = PORT_TYPE_BLUEtoothMFI;
            break;
            
        default:
            break;
    }
    [self.IPAddr  setText:@""];
   // [_printer_port release];
    _printer_port = nil;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if ([string isEqualToString:@"\n"])
    {
        [self.IPAddr  resignFirstResponder];
        return NO;
    } 
    return YES;
}
- (IBAction)customTest:(id)sender {
    TestController * testVC = [[TestController alloc]init];
    testVC.pos_sdk = self.pos_sdk;
    [self presentViewController:testVC animated:YES completion:^{
        [testVC release];
    }];
}

- (void)viewDidUnload
{
    [self setTextPrint:nil];
    [self setBarcodePrint:nil];
    [self setPDF417Print:nil];
    [self setMaxicodePrint:nil];
    [self setGS1DataBarPrint:nil];
    [self setStandardModePrint:nil];
    [self setPageModePrint:nil];
    [self setRasterImageprint:nil];
    [self setImagePrint:nil];
    [self setConnectPrinter:nil];
    [self setQRPrint:nil];
    [self setSearchPrinterButton:nil];
    [self setIPAddr:nil];
    [self setImageRAMorFlash:nil];
    [self setTextRasterPrintButton:nil];
    [self setUserDefinedCharacterButton:nil];
    [self setDownloadFileButton:nil];
    
    [port_info_set removeAllObjects];
    [port_info_set release];
    [super viewDidUnload];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
	[super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
	[super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) 
    {
        return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
    } 
    else 
    {
        return YES;
    }
}

//**********************************************************************************************
// Press "0" Button to connect printer
- (IBAction)PrinterConnect:(id)sender 
{
	SInt32 error_code = SUCCESS;
	
	//connect to printer
	if([[self.ConnectPrinter currentTitle] isEqual: @"Connect"])
    {
        

        if(selectedPortType == PORT_TYPE_WIFI){
            
            NSString *port_info = [self.IPAddr text];
            error_code = [self.printer_port openPort:port_info TimeOut:TIME_OUT_CONNECT];
            
        }else if(selectedPortType == PORT_TYPE_BluetoothBLE){
            
            error_code = [self.printer_port openPort:self.IPAddr.text];
            
        }else if(selectedPortType == PORT_TYPE_BLUEtoothMFI){
            
            for(NSInteger index = 0; index != [port_info_set count]; index++){
                if (![[port_info_set objectAtIndex:index] isKindOfClass:[EAAccessory class]]) {
                    AlertViewShow(@"Open Port ERROR");
                    goto ExitLine;
                }
            }
            
            EAAccessory *accessory = [port_info_set objectAtIndex:self.selectedSearchPrinter];
            
            //[self doSelectProtocol:sender accessory:accessory];
            self.selectedProtocolIndex = 0;
            
            error_code = [self.printer_port openPort:accessory protocolString:accessory.protocolStrings[self.selectedProtocolIndex]];
        }
        
		if(error_code != SUCCESS)
		{
            AlertViewShow(@"Open Port ERROR");
			goto ExitLine;
		}
		
        [self.printer_port recordCommunicationDataEnable:@"DataFile.dat"];
		[self.pos_sdk systemSetPortIO:self.printer_port];
        
        error_code = [self.pos_sdk systemReset];
        error_code = [self.pos_sdk systemSetEncoding:kCFStringEncodingGB_18030_2000];
		error_code = [self.pos_sdk systemFeedLine:1];
        
		if(error_code != SUCCESS)
		{
			[self.pos_sdk systemSetPortIO:nil];
			error_code = [self.printer_port closePort];
            AlertViewShow(@"Open port SUCCESS,but write data failed ");
			goto  ExitLine;
		}
		
		[self.ConnectPrinter setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
		[self.ConnectPrinter setTitle:@"Disconnect" forState:UIControlStateNormal];
		
        AlertViewShow(@"Connect Printer SUCCESS");
        
        ButtonEnableAndAlpha(self.selectPortTypeSegmented, 0, 0.5);
        ButtonEnableAndAlpha(self.SearchPrinterButton, 0, 0.5);
        ButtonEnableAndAlpha(self.IPAddr, 0, 0.5);
        ButtonEnableAndAlpha(self.TextPrint, 1, 1);
        ButtonEnableAndAlpha(self.BarcodePrint, 1, 1);
        ButtonEnableAndAlpha(self.PDF417Print, 1, 1);
        ButtonEnableAndAlpha(self.MaxicodePrint, 1, 1);
        ButtonEnableAndAlpha(self.GS1DataBarPrint, 1, 1);
        ButtonEnableAndAlpha(self.standardModePrint, 1, 1);
        ButtonEnableAndAlpha(self.pageModePrint, 1, 1);
        ButtonEnableAndAlpha(self.RasterImageprint, 1, 1);
        ButtonEnableAndAlpha(self.ImagePrint, 1, 1);
        ButtonEnableAndAlpha(self.QRPrint, 1, 1);
        ButtonEnableAndAlpha(self.ImageRAMorFlash, 1, 1);
        ButtonEnableAndAlpha(self.TextRasterPrintButton, 1, 1);
        ButtonEnableAndAlpha(self.UserDefinedCharacterButton, 1, 1);
        ButtonEnableAndAlpha(self.DownloadFileButton, 1, 1);
       // ButtonEnableAndAlpha(self.ToCustomButton, 1, 1);
	}
	//disconnect
	else
	{
		[self.pos_sdk systemSetPortIO:nil];
		error_code = [self.printer_port closePort];
		
		[self.ConnectPrinter setTitleColor:[UIColor greenColor] forState:UIControlStateNormal];
		[self.ConnectPrinter setTitle:@"Connect" forState:UIControlStateNormal];
		
        AlertViewShow(@"Disconnect Printer SUCCESS");
        
        ButtonEnableAndAlpha(self.selectPortTypeSegmented, 1, 1);
        ButtonEnableAndAlpha(self.SearchPrinterButton, 1, 1);
        ButtonEnableAndAlpha(self.IPAddr, 1, 1);
        ButtonEnableAndAlpha(self.TextPrint, 0, 0);
        ButtonEnableAndAlpha(self.BarcodePrint, 0, 0);
        ButtonEnableAndAlpha(self.PDF417Print, 0, 0);
        ButtonEnableAndAlpha(self.MaxicodePrint, 0, 0);
        ButtonEnableAndAlpha(self.GS1DataBarPrint, 0, 0);
        ButtonEnableAndAlpha(self.standardModePrint, 0, 0);
        ButtonEnableAndAlpha(self.pageModePrint, 0, 0);
        ButtonEnableAndAlpha(self.RasterImageprint, 0, 0);
        ButtonEnableAndAlpha(self.ImagePrint, 0, 0);
        ButtonEnableAndAlpha(self.QRPrint, 0, 0);
        ButtonEnableAndAlpha(self.ImageRAMorFlash, 0, 0);
		ButtonEnableAndAlpha(self.TextRasterPrintButton, 0, 0);
        ButtonEnableAndAlpha(self.UserDefinedCharacterButton, 0, 0);
        ButtonEnableAndAlpha(self.DownloadFileButton, 0, 0);
        ButtonEnableAndAlpha(self.ToCustomButton, 0, 0);
	}
    
ExitLine:
	return;
}

- (void)doSelectProtocol:(id)sender accessory:(EAAccessory*)accessory{
    PickerActionDoneButton done = ^(ButtonPullDownRealize *picker, NSInteger selectedIndex, id selectedValue){
        self.selectedProtocolIndex = selectedIndex;
    };
    
    PickerActionCancelButton cancel = ^(ButtonPullDownRealize *picker){
    };
    
    [ButtonPullDownRealize sheetPickerTitle:@"Select Protocol" Sheet:accessory.protocolStrings Selected:0 DoneButton:done CancelButton:cancel Action:sender];
}

//**********************************************************************************************
// Press "Search Printer" Button to search available printers
- (IBAction)SearchPrinter:(id)sender 
{
	PortInfoWIFI	*port_info     = nil;
	SInt32			index          = 0;
	
    ButtonEnableAndAlpha(self.selectPortTypeSegmented, 0, 0.5);
    self.IPAddr.enabled = NO;
    self.ConnectPrinter.enabled = NO;
    
    [self.array_SearchPrinter removeAllObjects];
     self.selectedSearchPrinter = 0;
    
    if(port_info_set){
        [port_info_set removeAllObjects];
        [port_info_set release];
        port_info_set = nil;
    }
    
	port_info_set = [self.printer_port searchPort];
	if(port_info_set == nil){
        AlertViewShow(@"No Printer Found");
		goto  ExitLine;
	}
    
    
    if(selectedPortType == PORT_TYPE_WIFI){
        for(index = 0; index != [port_info_set count]; index++){
            port_info = [port_info_set objectAtIndex:index];
            [self.array_SearchPrinter addObject:port_info.IPAddr];
        }
    }else if(selectedPortType == PORT_TYPE_BluetoothBLE){
        for(index = 0; index != [port_info_set count]; index++){
            BlueToothPeripheral *tmPeripheral = [port_info_set objectAtIndex:index];
            if (tmPeripheral.advName) {
                [self.array_SearchPrinter addObject:tmPeripheral.advName];
            }
        }
    }else if(selectedPortType == PORT_TYPE_BLUEtoothMFI){
        for(index = 0; index != [port_info_set count]; index++){
            EAAccessory *accessory = [port_info_set objectAtIndex:index];
            [self.array_SearchPrinter addObject:accessory.name];
        }
    }
    
    PickerActionDoneButton done = ^(ButtonPullDownRealize *picker, NSInteger selectedIndex, id selectedValue){
       
        self.selectedSearchPrinter = selectedIndex;  
        [self.IPAddr setText:selectedValue];
    };
    
    PickerActionCancelButton cancel = ^(ButtonPullDownRealize *picker){
    };
    
    [ButtonPullDownRealize sheetPickerTitle:@"Available Printers List" Sheet:self.array_SearchPrinter Selected:self.selectedSearchPrinter DoneButton:done CancelButton:cancel Action:sender];
    
    self.IPAddr.enabled = YES;
    self.ConnectPrinter.enabled = YES;
    ButtonEnableAndAlpha(self.selectPortTypeSegmented, 1, 1);
ExitLine:
    self.IPAddr.enabled = YES;
    self.ConnectPrinter.enabled = YES;
    ButtonEnableAndAlpha(self.selectPortTypeSegmented, 1, 1);
	return;
}

//**********************************************************************************************
// Press "Text" Button to jump to the subview about printing text
- (IBAction)Text:(id)sender 
{
    Text *viewController = [[[Text alloc] initWithNibNamePOSSDK:@"Text" pos_sdk:self.pos_sdk bundle:nil] autorelease];
    [self presentViewController:viewController animated:YES completion:nil];
	
}

//**********************************************************************************************
// Press "Barcode" Button to jump to the subview about printing barcode BarcodeUPC-A\BarcodeUPC-E\
//               BarcodeJAN13orEAN13\BarcodeJAN8orEAN8\BarcodeCODE39\BarcodeITF\BarcodeCODABAR\BarcodeCODE93\BarcodeCODE128
- (IBAction)Barcode:(id)sender 
{
    Barcode *viewController = [[[Barcode alloc] initWithNibNamePOSSDK:@"Barcode" pos_sdk:self.pos_sdk bundle:nil] autorelease];
    [self presentViewController:viewController animated:YES completion:nil];
}

//**********************************************************************************************
// Press "PDF417" Button to jump to the subview about printing PDF417
- (IBAction)PDF417:(id)sender
{
    PDF417 *viewController = [[[PDF417 alloc] initWithNibNamePOSSDK:@"PDF417" pos_sdk:self.pos_sdk bundle:nil] autorelease];
    [self presentViewController:viewController animated:YES completion:nil];
	
ExitLine:
    return;
}

//**********************************************************************************************
// Press "Maxicode" Button to print Maxicode
- (IBAction)Maxicode:(id)sender 
{
    SInt32   error_code = SUCCESS;    
    NSString *String    = nil;   
	NSData   *Data      = nil;
	String = @"1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ";

	NSStringEncoding enc= CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
	Data = [String dataUsingEncoding:enc];
    
    error_code = [self.pos_sdk barcodePrintMaxicode:Data];
    if (error_code == SUCCESS) 
    {
        AlertViewShow(@"SUCCESS!\n Data = 1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ");
    }
    else
    {
        AlertViewShow(@"ERROR TimeOut! Please reconnect Printer.");
    }
    
Exiline:
    return;
}

//**********************************************************************************************
// Press "GS1 Data Bar" Button to jump to the subview about printing GS1 Data Bar
- (IBAction)GS1DataBar:(id)sender 
{
    GS1DataBar *viewController = [[[GS1DataBar alloc] initWithNibNamePOSSDK:@"GS1DataBar" pos_sdk:self.pos_sdk bundle:nil] autorelease];
    [self presentViewController:viewController animated:YES completion:nil];
	
}

//**********************************************************************************************
// Press "standard Mode" Button to jump to the subview about set parate
- (IBAction)standardMode:(id)sender
{
    standardMode *viewController = [[[standardMode alloc] initWithNibNamePOSSDK:@"standardMode" pos_sdk:self.pos_sdk bundle:nil] autorelease];
    [self presentViewController:viewController animated:YES completion:nil];
ExitLine:
    return;
 }

- (IBAction)pageMode:(id)sender 
{
    SInt32   error_code         = SUCCESS;
    NSString *text_content      = nil;
    NSString *string            = nil;
    NSData   *data              = nil;
    NSString *PDF417_string     = nil;
    NSData   *PDF417_data       = nil;
    NSString *Maxicode_string   = nil;
    NSData   *Maxicode_data     = nil;
//    NSString *QR_string         = nil;
//    NSData   *QR_data           = nil;
//    NSString *GS1DataBar_string = nil;
//    NSData   *GS1DataBar_data   = nil;
//	NSString *image_name1       = nil;
//    NSString *full_path1        = nil;
//    UIImage  *image1            = nil;
//	NSString *image_name2       = nil;
//    NSString *full_path2        = nil;
//    UIImage  *image2            = nil;
//    NSString *image_name3       = nil;
//    NSString *full_path3        = nil;
//    UIImage  *image3            = nil;
//	NSMutableArray *image_set   = nil;
    
    error_code = [self.pos_sdk systemReset];//System Reset
    if (error_code != SUCCESS) 
    {
        AlertViewShow(@"ERROR TimeOut! Please reconnect Printer.");
        goto ExitLine;
    }

    error_code = [self.pos_sdk systemSelectPrintMode:PrintModePage];//Enter page mode
 
    //**********************************************************************************************
	//Print text in page mode    
    error_code = [self.pos_sdk pageModeSetPrintArea:50 Y:0 AreaWidth:580 AreaHeight:600 PrintDirection:LeftToRight];//Set print area in page mode
    error_code = [self.pos_sdk pageModeSetStartingPosition:0 Y:100];//Set Starting Position in page mode
	text_content = @"We strive to be the expert supplier of printers.Our POS series printers can print text,image and barcode.It's a wise choice for you to choose our printers.";
    error_code = [self.pos_sdk textPrint:text_content];
     
    error_code = [self.pos_sdk pageModeSetStartingPosition:100 Y:350];//Set Starting Position in page mode
    error_code = [self.pos_sdk textSelectFont:FontTypeStandardASCII FontStyle:FontStyleReverse];
    error_code = [self.pos_sdk textPrint:text_content];
	
    error_code = [self.pos_sdk pageModePrint];
    error_code = [self.pos_sdk pageModeClearBuffer];
    
    error_code = [self.pos_sdk pageModeSetPrintArea:100 Y:0 AreaWidth:400 AreaHeight:1100 PrintDirection:LeftToRight];//Set print area in page mode
    error_code = [self.pos_sdk pageModeSetStartingPosition:50 Y:100];//Set Starting Position in page mode
    error_code = [self.pos_sdk textSelectFont:FontTypeCompressedASCII FontStyle:FontStyleBold];
    error_code = [self.pos_sdk textPrint:text_content];
    
    error_code = [self.pos_sdk pageModeSetStartingPosition:0 Y:400];//Set Starting Position in page mode
    error_code = [self.pos_sdk textSelectFont:FontTypeCompressedASCII FontStyle:FontStyleUnderlineTwoDotThick];
    error_code = [self.pos_sdk textPrint:text_content];
	
    error_code = [self.pos_sdk pageModeSetStartingPosition:0 Y:700];//Set Starting Position in page mode
    error_code = [self.pos_sdk textSelectFontMagnifyTimes:3 VerticalTimes:2];
    error_code = [self.pos_sdk textPrint:text_content];
    
    error_code = [self.pos_sdk pageModePrint];
    error_code = [self.pos_sdk pageModeClearBuffer];
    
    //Print barcode
	string     = @"012345678912";
    data       = [string dataUsingEncoding:NSUTF8StringEncoding];
    error_code = [self.pos_sdk pageModeSetPrintArea:100 Y:0 AreaWidth:640 AreaHeight:700 PrintDirection:LeftToRight];
    error_code = [self.pos_sdk pageModeSetStartingPosition:0 Y:200];
    error_code = [self.pos_sdk barcodePrint1Dimension:data BarcodeType:BarcodeUPC_A ModuleWidth:3 BarcodeHeight:100 HriFontType:FontTypeStandardASCII HriPosition:HRIBelow];
	
    error_code = [self.pos_sdk pageModeSetStartingPosition:0 Y:500];
    error_code = [self.pos_sdk barcodePrint1Dimension:data BarcodeType:BarcodeJAN13orEAN13 ModuleWidth:3 BarcodeHeight:100 HriFontType:FontTypeStandardASCII HriPosition:HRIBelow];
    
    error_code = [self.pos_sdk pageModePrint];
    error_code = [self.pos_sdk pageModeClearBuffer];
    
	PDF417_string = @"1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    PDF417_data   = [PDF417_string dataUsingEncoding:NSUTF8StringEncoding];
    error_code    = [self.pos_sdk pageModeSetPrintArea:0 Y:0 AreaWidth:640 AreaHeight:1100 PrintDirection:LeftToRight];
    error_code    = [self.pos_sdk pageModeSetStartingPosition:0 Y:300];
    error_code    = [self.pos_sdk barcodePrintPDF417:PDF417_data AppearanceToHeight:1 AppearanceToWidth:1 RowNumber:3 ColumnNumber:1 XSize:4 LineHeight:5 CorrectionGrade:0];
    
	Maxicode_string = @"1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    Maxicode_data   = [Maxicode_string dataUsingEncoding:NSUTF8StringEncoding];
    error_code = [self.pos_sdk pageModeSetStartingPosition:0 Y:1000];
    error_code = [self.pos_sdk barcodePrintMaxicode:Maxicode_data];
	
    error_code = [self.pos_sdk pageModePrint];
    error_code = [self.pos_sdk pageModeClearBuffer];
    
//    error_code = [self.pos_sdk pageModeSetPrintArea:0 Y:0 AreaWidth:640 AreaHeight:1500 PrintDirection:LeftToRight];
//    error_code = [self.pos_sdk pageModeSetStartingPosition:100 Y:300];
//	QR_string  = @"QA,AABCDEFGHIJKLMN1234567890";
//    QR_data    = [QR_string dataUsingEncoding:NSUTF8StringEncoding];    
//    error_code = [self.pos_sdk barcodePrintQR:QR_data BasicElementWidth:5 SymbolType:EnhancedType LanguageMode:LanguageChinese];
//
//	 
//    error_code        = [self.pos_sdk pageModeSetStartingPosition:100 Y:1100];
//	GS1DataBar_string = @"0123456789012";
//    GS1DataBar_data   = [GS1DataBar_string dataUsingEncoding:NSUTF8StringEncoding];    
//    error_code = [self.pos_sdk barcodePrintGS1DataBar:GS1DataBar_data BarcodeType:GS1DataBarExpandedStacked BasicElementWidth:3 BarcodeHeight:100 SegmentNumber:2 SeparatorHeight:2 BasicElementHeight:4 HRI:OnlyDataBarHri UseAI:1];
//	
//    error_code = [self.pos_sdk pageModePrint];
//    error_code = [self.pos_sdk pageModeClearBuffer];
  
//    //**********************************************************************************************
//    //Print RAM Image    
//    error_code = [self.pos_sdk pageModeSetPrintArea:0 Y:0 AreaWidth:640 AreaHeight:2600 PrintDirection:LeftToRight];
//    error_code = [self.pos_sdk pageModeSetStartingPosition:10 Y:200];
//    error_code = [self.pos_sdk textSelectFontMagnifyTimes:1 VerticalTimes:1];
//    error_code = [self.pos_sdk textPrint:@"Print RAM Image"];
//    
//    //Download RAM Image
//    image_name1 = @"";
//    full_path1  = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:image_name1];    
//    image1      = [[UIImage alloc] initWithContentsOfFile:full_path1];
//    error_code  = [self.pos_sdk  imageDownloadToPrinterRAM:1 Image:image1 PrinterWidth:640];
//    image_name2 = @"color.bmp";
//    full_path2  = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:image_name2];    
//    image2      = [[UIImage alloc] initWithContentsOfFile:full_path2];
//    error_code  = [self.pos_sdk  imageDownloadToPrinterRAM:2 Image:image2 PrinterWidth:640];
//    image_name3 = @"Jpg.jpg";
//	full_path3  = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:image_name3];    
//    image3      = [[UIImage alloc] initWithContentsOfFile:full_path3];
//    error_code  = [self.pos_sdk  imageDownloadToPrinterRAM:3 Image:image3 PrinterWidth:640];
//    
//    //Print RAM Image
//    error_code = [self.pos_sdk pageModeSetStartingPosition:100 Y:650];
//    error_code = [self.pos_sdk imageRAMPrint:3 Mode:NormalMode];
//    error_code = [self.pos_sdk pageModeSetStartingPosition:0 Y:1300];
//    error_code = [self.pos_sdk imageRAMPrint:1 Mode:Double_height];
//    error_code = [self.pos_sdk pageModeSetStartingPosition:0 Y:2500];
//    error_code = [self.pos_sdk imageRAMPrint:2 Mode:Quadruple];
//    
//    error_code = [self.pos_sdk pageModePrint];
//    error_code = [self.pos_sdk pageModeClearBuffer];
//    
//    //**********************************************************************************************
//    //Print Flash Image
//    error_code = [self.pos_sdk pageModeSetPrintArea:0 Y:0 AreaWidth:640 AreaHeight:200 PrintDirection:LeftToRight];
//    error_code = [self.pos_sdk pageModeSetStartingPosition:50 Y:150];
//    error_code = [self.pos_sdk textPrint:@"Print Flash Image"];
//    error_code = [self.pos_sdk pageModePrint];
//    
//    image_set = [[NSMutableArray alloc] init];
//    [image_set addObject:image1];
//    [image_set addObject:image2];
//    [image_set addObject:image3];
//    
//    [image1 release];
//    [image2 release];
//    [image3 release];
//
//    error_code = [self.pos_sdk imageDownloadToPrinterFlash:image_set PrinterWidth:640];
//    error_code = [self.pos_sdk pageModeSetStartingPosition:10 Y:300];
//    error_code = [self.pos_sdk imageFlashPrint:1 Mode:NormalMode];
//    error_code = [self.pos_sdk pageModeSetStartingPosition:10 Y:600];
//    error_code = [self.pos_sdk imageFlashPrint:2 Mode:Double_height];
//    error_code = [self.pos_sdk pageModeSetStartingPosition:10 Y:900];
//    error_code = [self.pos_sdk imageFlashPrint:3 Mode:Quadruple];
//    
//    error_code = [self.pos_sdk pageModePrint];
//    error_code = [self.pos_sdk pageModeClearBuffer];
//    [image_set release];
    error_code = [self.pos_sdk systemReset];
ExitLine:   
    return;
}

- (IBAction)RasterImage:(id)sender 
{
    RasterImage *viewController = [[[RasterImage alloc] initWithNibNamePOSSDK:@"RasterImage" pos_sdk:self.pos_sdk bundle:nil] autorelease];
    [self presentViewController:viewController animated:YES completion:nil];
}

- (IBAction)Image:(id)sender
{
    Image *viewController = [[[Image alloc] initWithNibNamePOSSDK:@"Image" pos_sdk:self.pos_sdk bundle:nil] autorelease];
    [self presentViewController:viewController animated:YES completion:nil];
}

- (IBAction)barcodeQR:(id)sender 
{
    barcodeQR *viewController = [[[barcodeQR alloc] initWithNibNamePOSSDK:@"barcodeQR" pos_sdk:self.pos_sdk bundle:nil] autorelease];
    [self presentViewController:viewController animated:YES completion:nil];
}

- (IBAction)ImageRAMorFlash:(id)sender
{
    RAMorFlashImage *viewController = [[[RAMorFlashImage alloc] initWithNibNamePOSSDK:@"RAMorFlashImage" pos_sdk:self.pos_sdk bundle:nil] autorelease];
    [self presentViewController:viewController animated:YES completion:nil];
}

- (IBAction)TextRasterprint:(id)sender
{
    TextRasterprint *viewController = [[[TextRasterprint alloc] initWithNibNamePOSSDK:@"TextRasterprint" pos_sdk:self.pos_sdk bundle:nil] autorelease];
    [self presentViewController:viewController animated:YES completion:nil];
}

- (IBAction)UserDefinedCharacter:(id)sender
{
    SInt32	error_code = SUCCESS;
	SInt32	BytesOfHeight, DotsOfWidth, StartingCode = 'A', EndingCode = 'B';
	NSMutableData *CharacterData = nil;
	SInt32		  index          = 0;
	UIImage		  *image         = nil;
	NSString	  *image_name[2] = {@"1.bmp", @"2.bmp"};
	NSString      *full_path     = nil;
	
	CharacterData = [[NSMutableData alloc] initWithCapacity:10240];
    error_code = [self.pos_sdk systemReset];
    if (error_code != SUCCESS) 
    {
        AlertViewShow(@"ERROR TimeOut! Please reconnect Printer.");
		goto ExitLine;
    }
	
	for(index = StartingCode; index <= EndingCode; index++)
	{
		full_path = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:image_name[index - StartingCode]];
		image = [[UIImage alloc] initWithContentsOfFile:full_path];
        
		ImageDataRef image_data = {0};
        
		[self.pos_sdk imageFormatConvertToUserDefinedData:image ditheringSupported:FALSE image_data:&image_data];
        
		BytesOfHeight	= image_data.image_height >> 3;
		DotsOfWidth		= image_data.image_width;
		[CharacterData appendBytes:image_data.data_buf length:image_data.image_data_len];
        
		if(image_data.data_buf != nil)	{free(image_data.data_buf);}
		if(image != nil)	            {[image release];}
	}
	
	error_code = [self.pos_sdk textUserDefinedCharacterDefine:BytesOfHeight DotsOfWidth:DotsOfWidth StartingCode:StartingCode EndingCode:EndingCode CharacterData:CharacterData];

   	error_code = [self.pos_sdk textUserDefinedCharacterEnable:1];
    error_code = [self.pos_sdk textSelectFontMagnifyTimes:3 VerticalTimes:3];
    error_code = [self.pos_sdk textPrint:@"123AACBB123"];
    
    error_code = [self.pos_sdk systemFeedLine:1];
    
    error_code = [self.pos_sdk textUserDefinedCharacterCancel:StartingCode];
    error_code = [self.pos_sdk textPrint:@"123AACBB123"];
    error_code = [self.pos_sdk systemFeedLine:1];
    
    error_code = [self.pos_sdk textUserDefinedCharacterEnable:0];
    error_code = [self.pos_sdk textSelectFontMagnifyTimes:3 VerticalTimes:3];
    error_code = [self.pos_sdk textPrint:@"123AACBB123"];
    error_code = [self.pos_sdk systemFeedLine:1];
    
    error_code = [self.pos_sdk systemCutPaper:CutPartAfterFeed FeedDistance:50];
    
ExitLine:
    if(CharacterData != nil)	{[CharacterData release];}
    return;
}



- (void)dealloc
{
	[self.TextPrint release];
    [self.BarcodePrint release];
    [self.PDF417Print release];
    [self.MaxicodePrint release];
    [self.GS1DataBarPrint release];
    [self.standardModePrint release];
    [self.pageModePrint release];
    [self.RasterImageprint release];
    [self.ImagePrint release];
    [self.ConnectPrinter release];
    [self.QRPrint release];
    [self.SearchPrinterButton release];
    [self.IPAddr release];
    [self.ImageRAMorFlash release];
    [self.TextRasterPrintButton release];
    [self.UserDefinedCharacterButton release];
    [self.array_SearchPrinter release];
	[self.DownloadFileButton release];
    [self.ToCustomButton release];
    if (_printer_port != nil)
	{
		[_printer_port closePort];
		[_printer_port release];
		_printer_port = nil;
	}
	
	if (_pos_sdk != nil)
	{
		[_pos_sdk release];
		_pos_sdk = nil;
	}
	
	[self.array_DeviceList release];

    [_selectPortTypeSegmented release];
    [_ToCustomButton release];
    [super dealloc];
}

- (IBAction)DownloadFile:(id)sender 
{
	SInt32	error_code = SUCCESS;
    NSString* full_path = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:@"sample1.dat"];
    
    error_code = [self.pos_sdk systemDownloadFile:full_path DownloadTimeOut:3];
	if (error_code != SUCCESS)
    {
		AlertViewShow(@"ERROR TimeOut! Please reconnect Printer.");
    }
}
@end
