//
//  Sample.m
//  SiiLibSample
//

#import "SampleFunctions.h"
#import <SIIPrinterManager/SIISmartLabelManager.h>
#import "SampleValue.h"
#import "DisplayData.h"

BOOL _printerDiscoveryCompletion;
NSString *_resultMessage;
SIIPrinterManager *_printerManager;
SIISmartLabelManager *_labelManager;

@implementation SampleFunctions

/// Initial settings when view is loaded
+ (void)InitialSetting {
    _printerDiscoveryCompletion = NO;
    _resultMessage = @"";
    _printerManager = [[SIIPrinterManager alloc] init];
    _labelManager = [[SIISmartLabelManager alloc] init];
}

/// Sample for connecting to printer
+ (BOOL)connectSample:(NSInteger)model address:(NSString *)address type:(NSInteger)type {
    _resultMessage = STR_SUCCEEDED;
    @try {
        [_printerManager connect:model address:address portType:type];
    }
    @catch (SIIPrinterException *e) {
        _resultMessage = [self getErrorMessage:e.errorCode];
        return NO;
    }
    return YES;
}

/// Sample for disconnect
+ (BOOL)disconnectSample {
    _resultMessage = STR_SUCCEEDED;
    @try {
        // Get printer response before disconnect is recommended
        [self response_request];
        [_printerManager disconnect];
    }
    @catch (SIIPrinterException *e) {
        _resultMessage = [self getErrorMessage:e.errorCode];
        return NO;
    }
    return YES;
}

/// Sample for printing a stand mode sample receipt
+ (BOOL)standardModeSample {
    _resultMessage = STR_SUCCEEDED;

    // Store internationalCharacter and codePage settings and reset the settings at the end of the process.
    NSInteger internationalCharacter = _printerManager.internationalCharacter;
    NSInteger codePage = _printerManager.codePage;
    @try{
        NSString *lang = [[NSLocale preferredLanguages] objectAtIndex:0];
        NSMutableString *receiptStr =[NSMutableString stringWithCapacity:10];
        
        // Get current system language to set language for receipt
        if ([lang hasPrefix:@"ja"] == YES) {
            //  Set internationalCharacter and codePage of printer to Japanese for printing a Japanese receipt
            _printerManager.internationalCharacter = SII_PM_COUNTRY_JAPAN;
            _printerManager.codePage =  SII_PM_CODE_PAGE_KATAKANA;
            [receiptStr appendString:@"\n"];
            [receiptStr appendString:@"--------------------------------\n"];
            [receiptStr appendString:@"ｸﾞﾘﾙﾄﾞﾁｷﾝﾌﾞﾚｽﾄ            ¥1,850\n"];
            [receiptStr appendString:@"ｻｰﾛｲﾝｽﾃｰｷ                 ¥3,200\n"];
            [receiptStr appendString:@"ﾛｰｽﾄﾗﾑ                    ¥2,000\n"];
            [receiptStr appendString:@"ｻﾗﾀﾞ                      ¥1,000\n"];
            [receiptStr appendString:@"ｸｯｷｰ                        ¥350\n"];
            [receiptStr appendString:@"ｸｯｷｰ                        ¥350\n"];
            [receiptStr appendString:@"ｱｲｽｸﾘｰﾑ                     ¥500\n"];
            [receiptStr appendString:@"ﾁｭｳｶｿﾊﾞ                   ¥1,500\n"];
            [receiptStr appendString:@"ｽｷﾔｷ                      ¥3,000\n"];
            [receiptStr appendString:@"ｻﾝﾄﾞｲｯﾁ                   ¥1,000\n"];
            [receiptStr appendString:@"ﾋﾟｻﾞ                      ¥2,000\n"];
            [receiptStr appendString:@"ｺｳﾁｬ                        ¥350\n"];
            [receiptStr appendString:@"ｺｰﾋｰ                        ¥350\n"];
            [receiptStr appendString:@"\n"];
            [receiptStr appendString:@"--------------------------------\n"];
            [receiptStr appendString:@"        小計             ¥17,450\n"];
            [receiptStr appendString:@"        消費税            ¥1,745\n"];
            [receiptStr appendString:@"        合計             ¥19,195\n"];
            [receiptStr appendString:@"\n"];
            [receiptStr appendString:@"        お預かり         ¥20,000\n"];
            [receiptStr appendString:@"        お釣り              ¥805\n"];
            [receiptStr appendString:@"\n"];
            [receiptStr appendString:@"ご利用ありがとうございます\n"];
            [receiptStr appendString:@"またのご利用をお待ちしております\n\n"];
        } else {
            //  Set internationCharacter and codePage of printer to English for printing an English receipt
            _printerManager.internationalCharacter = SII_PM_COUNTRY_USA;
            _printerManager.codePage = SII_PM_CODE_PAGE_1252;
            [receiptStr appendString:@"\n"];
            [receiptStr appendString:@"--------------------------------\n"];
            [receiptStr appendString:@"GRILLED CHICKEN BREAST    $18.50\n"];
            [receiptStr appendString:@"SIRLOIN STEAK             $32.00\n"];
            [receiptStr appendString:@"ROAST LAMB                $20.00\n"];
            [receiptStr appendString:@"SALAD                     $10.00\n"];
            [receiptStr appendString:@"COKE                       $3.50\n"];
            [receiptStr appendString:@"COKE                       $3.50\n"];
            [receiptStr appendString:@"ICE CREAM                  $5.00\n"];
            [receiptStr appendString:@"CHINESE NOODLE            $15.00\n"];
            [receiptStr appendString:@"SUKIYAKI                  $30.00\n"];
            [receiptStr appendString:@"SANDWICH                  $10.00\n"];
            [receiptStr appendString:@"PIZZA                     $20.00\n"];
            [receiptStr appendString:@"TEA                        $3.50\n"];
            [receiptStr appendString:@"COFFEE                     $3.50\n"];
            [receiptStr appendString:@"\n"];
            [receiptStr appendString:@"--------------------------------\n"];
            [receiptStr appendString:@"        SUBTOTAL         $174.50\n"];
            [receiptStr appendString:@"        SALES TAX          $8.73\n"];
            [receiptStr appendString:@"        TOTAL            $183.23\n"];
            [receiptStr appendString:@"\n"];
            [receiptStr appendString:@"        CASH             $200.00\n"];
            [receiptStr appendString:@"        CHANGE DUE        $16.77\n"];
            [receiptStr appendString:@"\n"];
            [receiptStr appendString:@"Thank you and see you again!\n\n"];
        }
        // Print image with center alignment and dithering
        NSString *path = [[NSBundle mainBundle] pathForResource:@"logo" ofType:@"jpg"];
        [_printerManager sendDataFile:path alignment:SII_PM_ALIGNMENT_CENTER dithering:SII_PM_DITHERING_ERRORDIFFUSION];
        
        // Get current date
        NSString* date_converted;
        NSDate* date_source = [NSDate date];
        NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"YYYY-MM-dd hh:mm:ss"];
        date_converted = [formatter stringFromDate:date_source];
        NSMutableString *date_text = [NSMutableString stringWithCapacity:10];
        [date_text appendString: @"\n"];
        [date_text appendString: @"No.00001    "];
        [date_text appendString: date_converted];
        [date_text appendString: @"\n"];
        // Print current date with center alignment
        [_printerManager sendTextEx:date_text bold:SII_PM_BOLD_CANCEL underline:SII_PM_UNDERLINE_CANCEL reverse:SII_PM_REVERSE_CANCEL font:SII_PM_FONT_A scale:SII_PM_VARTICAL_1_HORIZONTAL_1 alignment:SII_PM_ALIGNMENT_CENTER];
        
        // Print receipt details with center alignment
        [_printerManager sendTextEx:receiptStr bold:SII_PM_BOLD_CANCEL underline:SII_PM_UNDERLINE_CANCEL reverse:SII_PM_REVERSE_CANCEL font:SII_PM_FONT_A scale:SII_PM_VARTICAL_1_HORIZONTAL_1 alignment:SII_PM_ALIGNMENT_CENTER];
        
        // DPU-S245 & DPU-S445
        if (_printerManager.printerModel == SII_PM_PRINTER_MODEL_DPU_S245 || _printerManager.printerModel == SII_PM_PRINTER_MODEL_DPU_S445 ) {
            // Print a QRcode
            NSString *qrData = @"QR Sample";
            [_printerManager printQRcode:qrData errorCorrection:SII_PM_QR_ERROR_CORRECTION_M moduleSize:SII_PM_QR_MODULE_SIZE_4 alignment:SII_PM_ALIGNMENT_LEFT model:SII_PM_QR_MODEL_2];
            
            // Print an EAN13 barcode
            [_printerManager printBarcode:SII_PM_BARCODE_EAN13 text:@"012345678901" moduleSize:SII_PM_BARCODE_MODULE_WIDTH_3 moduleHeight:80 hriPosition:SII_PM_HRI_POSITION_BELOW hriFont:SII_PM_FONT_A alignment:SII_PM_ALIGNMENT_LEFT];
        } else {
            // Print a QRcode
            NSString *qrData = @"QR Sample";
            [_printerManager printQRcode:qrData errorCorrection:SII_PM_QR_ERROR_CORRECTION_M moduleSize:SII_PM_QR_MODULE_SIZE_4 alignment:SII_PM_ALIGNMENT_CENTER model:SII_PM_QR_MODEL_2];
            
            // Print an EAN13 barcode
            [_printerManager printBarcode:SII_PM_BARCODE_EAN13 text:@"0123456789012" moduleSize:SII_PM_BARCODE_MODULE_WIDTH_3 moduleHeight:80 hriPosition:SII_PM_HRI_POSITION_BELOW hriFont:SII_PM_FONT_A alignment:SII_PM_ALIGNMENT_CENTER];
            /// Specify the barcode for CODE93 (Data:12345)
            /// How to binary input.
            /// 1. Input any data from 00H to 2EH. Multiple data can be input
            /// 2. Input 2FH or more lastly as the stop code
            //  UInt8 rawArray[6] = {0x01, 0x02, 0x03, 0x04, 0x05, 0x2F};
            //  NSData *data = [NSData dataWithBytes:rawArray length:sizeof(rawArray)];
            //  [_printerManager printBarcode:SII_PM_BARCODE_CODE93 data:data moduleSize:SII_PM_PDF417_MODULE_WIDTH_3 moduleHeight:80 hriPosition:SII_PM_HRI_POSITION_BELOW hriFont:SII_PM_FONT_A alignment:SII_PM_ALIGNMENT_CENTER];
            
            // Partial cut with pre-feed
            // If using printer does not have cutter, it will only feed paper
             [_printerManager cutPaper:SII_PM_CUT_PARTIAL];
        }
    } @catch (SIIPrinterException *e) {
        _resultMessage = [self getErrorMessage:e.errorCode];
        return NO;
    } @finally {
        // Reset the settings of internationalCharacter and codePage.
        _printerManager.internationalCharacter = internationalCharacter;
        _printerManager.codePage = codePage;
        // Get printer response to confirm printing is finished
        [self response_request];
    }
    return YES;
}

/// Sample for printing a page mode sample
+ (BOOL)printPageModeSample {
    @try {
        // Start page mode
        [_printerManager enterPageMode];
        
        // Specify the print area in page mode
        // The number of printable dots in one dot line has to be set to 355 dots for this sample code.
        [_printerManager setPageModeArea:0 y:0 width:355 height:576];
        
        // Specify the rectangle and the rule
        [_printerManager printPageModeRectangle:0 startY:0 endX:344 endY:575 lineStyle:SII_PM_LINESTYLE_THIN];
        [_printerManager printPageModeRectangle:7 startY:7 endX:336 endY:567 lineStyle:SII_PM_LINESTYLE_THIN];
        [_printerManager printPageModeLine:11 startY:404 endX:334 endY:404 lineStyle:SII_PM_LINESTYLE_THIN];
        
        // Specify the print direction in page mode
        [_printerManager setPageModeDirection:SII_PM_DIRECTION_TOP_TO_BOTTOM];
        
        // Specify the text
        [_printerManager printPageModeText:21 startY:47 text:@"No.123456789"];
        [_printerManager printPageModeText:212 startY:340 text:@"Date 2023-01-01"];
        
        // Specify the image file
        NSString *filePath = [[NSBundle mainBundle] pathForResource:@"TicketImage" ofType:@"jpg"];
        [_printerManager printPageModeImageFile:10 startY:222 fileName:filePath dithering:SII_PM_DITHERING_DISABLE];
        
        // Specify the print area in page mode
        [_printerManager setPageModeArea:0 y:404 width:345 height:163];
        
        // Specify the direction of the print
        [_printerManager setPageModeDirection:SII_PM_DIRECTION_LEFT_TO_RIGHT];
        
        // Specify the barcode for CODE128
        UInt8 rawArray[11] = {0x67, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x68};
        NSData *data = [NSData dataWithBytes:rawArray length:sizeof(rawArray)];
        [_printerManager printPageModeBarcode:20 startY:132 barcodeSymbol:SII_PM_BARCODE_CODE128 data:data moduleSize:SII_PM_BARCODE_MODULE_WIDTH_2 moduleHeight:80 hriPosition:SII_PM_HRI_POSITION_ABOVE hriFont:SII_PM_FONT_A];
        /// Specify the barcode for CODE128 (Data:123456789)
        /// How to input using the CODE128 Code Set table
        /// 1. Input the start code of 67H(Code Set A), 68H(Code Set B), or 69H(Code Set C) shown in the table of CODE128 Code Set
        /// 2. Input any data from 00H to 66H. Multiple data can be input
        /// 3. Input 67H or more lastly as the stop code
        //  UInt8 rawArray[11] = {0x68, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x67};
        //  NSData *data = [NSData dataWithBytes:rawArray length:sizeof(rawArray)];

        /// How to input using the CODE128 Special Code Set table
        /// 1. Input the start code (START A, START B, or START C) of the code set to be selected shown in the table of CODE128 Special Code
        /// 2. Input the data in the respective formats
        ///       Code Set A : Data from 00H to 5FH can be input
        ///       Code Set B : Data from 20H to 7FH can be input
        ///       Code Set C : Data from 00H(00) to 63H(99) can be input
        //  UInt8 rawArray[11] = {0x7B, 0x42, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39};
        //  NSData *data = [NSData dataWithBytes:rawArray length:sizeof(rawArray)];
        //  [_printerManager printPageModeBarcode:10 startY:132 barcodeSymbol:SII_PM_BARCODE_CODE128 data:data moduleSize:SII_PM_BARCODE_MODULE_WIDTH_2 moduleHeight:80 hriPosition:SII_PM_HRI_POSITION_ABOVE hriFont:SII_PM_FONT_A];
        
        // Print the page mode and partial cut with pre-feed
        // If using printer does not have cutter, it will only feed paper
        [_printerManager printPageMode:SII_PM_CUT_PARTIAL];
        _resultMessage = STR_SUCCEEDED;
    }
    @catch (SIIPrinterException *e) {
        _resultMessage = [self getErrorMessage:e.errorCode];
        return NO;
    } @finally {
        @try {
            // Exit page mode finally
            [_printerManager exitPageMode];
            // Get printer response to confirm printing is finished
            BOOL ret = [self response_request];
            if (ret != YES) {
                return NO;
            }
        } @catch (SIIPrinterException *e) {
        }
    }
    return YES;
}

+ (BOOL)smartLabelSample {
    _resultMessage = STR_SUCCEEDED;
    @try {
        // Specify a label file(*.sl) to print or replace data.
        // Sample.sl is defined following objects.
        //  * Text    Object (ID = 1) : "Jane Smith"
        //  * Image   Object (ID = 1) : woman.jpg
        //  * Barcode Object (ID = 1) : "0123456" (Code128)
        // Label Type of Sample.sl is User Paper[ Printer:MP-B21L, PaperType:Receipt, PositionDetection:None, PaperWidth58mm, PaperLength:300mm ].
        NSString *path = [[NSBundle mainBundle] pathForResource:@"Sample" ofType:@"sl"];
        [_labelManager selectSmartLabelFile:path];
        
        // Print Smart Label image
        [_printerManager printSmartLabelImageData:_labelManager];
        
        // Replace the text data with "John Smith".
        [_labelManager replaceSmartLabelTextData:1 text:@"John Smith"];
        
        // Get image data for replacement
        NSString *imagePath = [[NSBundle mainBundle] pathForResource: @"man" ofType:@"jpg"];
        UIImage *image = [UIImage imageWithContentsOfFile:imagePath];
        // Replace the image data with "man.jpg".
        [_labelManager replaceSmartLabelImageData:1 image:image];
        
        // Replace the barcode data with "ABCDEFG".
        [_labelManager replaceSmartLabelBarcodeData:1 text:@"ABCDEFG"];
        
        // Print Smart Label image
        [_printerManager printSmartLabelImageData:_labelManager];
        
        // Full cut with pre-feed.
        [_printerManager cutPaper:SII_PM_CUT_FULL];
    } @catch (SIIPrinterException *e) {
        _resultMessage = [self getErrorMessage:e.errorCode];
        return NO;
    } @finally {
        // Get printer response to confirm printing is finished
        BOOL ret = [self response_request];
        if (ret != YES) {
            return NO;
        }
    }
    return YES;
}

/// Call display sample functions for showing
+ (BOOL)displaySample {
    _resultMessage = STR_SUCCEEDED;
    DisplayData* displayData = [[DisplayData alloc] init];
    @try {
        [self displaySample_total:displayData.total];
        NSString *lang = [[NSLocale preferredLanguages] objectAtIndex:0];
        for(NSInteger i = 0; i < 5; i++) {
            [displayData pickAnItem:lang];
            [self displaySample_detail:displayData.total itemName:displayData.itemName price:displayData.itemPrice];
        }
        [displayData calculateTotal];
        [self displaySample_payment:displayData.total paid:displayData.paid change:displayData.change];
        [self displaySample_standby];
    } @catch (SIIPrinterException *e) {
        _resultMessage = [self getErrorMessage:e.errorCode];
        return NO;
    }
    return YES;
}

/// Sample for sending file to printer
+ (BOOL)sendDataFileSample:(NSString *)filePath {
    _resultMessage = STR_SUCCEEDED;
    @try {
        // Specifiy the print or data file.
        [_printerManager sendDataFile:filePath alignment:SII_PM_ALIGNMENT_LEFT];
    } @catch (SIIPrinterException *e) {
        _resultMessage = [self getErrorMessage:e.errorCode];
        return NO;
    } @finally {
        // Get printer response to confirm printing is finished
        BOOL ret = [self response_request];
        if (ret != YES) {
            return NO;
        }
    }
    return YES;
}

/// Sample for print PDF file.
+ (BOOL)printPDFSample:(NSString *)filePath {
    _resultMessage = STR_SUCCEEDED;
    @try {
        // Specifies the print PDF file.
        // To print all pages of a PDF file, set “startIndex” to -1.
        [_printerManager printPDF:filePath startIndex:-1 endIndex:-1 rotate:SII_PM_ROTATE_NONE imageScale:SII_PM_IMAGE_SCALE_WIDTH_FIT bottomMargin:-1 dithering:SII_PM_DITHERING_ERRORDIFFUSION alignment:SII_PM_ALIGNMENT_CENTER];
        // To print any page of a PDF file
        // Example: To print pages 2 through 5, specify 2 for “startIndex” and 5 for “endIndex”.
//        [_printerManager printPDF:filePath startIndex:2 endIndex:5 rotate:SII_PM_ROTATE_NONE imageScale:SII_PM_IMAGE_SCALE_WIDTH_FIT bottomMargin:-1 dithering:SII_PM_DITHERING_ERRORDIFFUSION alignment:SII_PM_ALIGNMENT_CENTER];
    } @catch (SIIPrinterException *e) {
        _resultMessage = [self getErrorMessage:e.errorCode];
        return NO;
    } @finally {
        // Get printer response to confirm printing is finished
        BOOL ret = [self response_request];
        if (ret != YES) {
            return NO;
        }
    }
    return YES;
}

/// Sample for opening external drawer
+ (BOOL)openDrawerSample {
    _resultMessage = STR_SUCCEEDED;
    @try {
        // Specify the drawer which to open.
        [_printerManager openDrawer:SII_PM_DRAWER_1 onOffTime:SII_PM_ON_OFF_TIME_500];
    }
    @catch (SIIPrinterException *e) {
        _resultMessage = [self getErrorMessage:e.errorCode];
        return NO;
    }
    return YES;
}

/// Sample for starting lan printer discovery
+ (void)startLanDiscoveryPrinterSample:(NSInteger)retryCount timeout:(NSInteger)timeout {
    _printerDiscoveryCompletion = NO;
    [_printerManager startDiscoveryPrinter:retryCount timeout:timeout completion:^(NSArray *printerList) {
        // Process while discovery complete
        [self performSelectorOnMainThread:@selector(setPrinterDiscoveryCompletion) withObject:nil waitUntilDone:NO];
    }];
    _resultMessage = STR_SUCCEEDED;
}

/// Sample for get lan printer discovery result
+ (void)setPrinterDiscoveryCompletion {
    _printerDiscoveryCompletion = YES;
}

/// Sample for starting bluetooth printer discovery
+ (BOOL)getPrinterDiscoveryCompletion {
    return _printerDiscoveryCompletion;
}

/// Sample for cancel printer discovery immediately
+ (void)cancelDiscoveryPrinterSample {
    [_printerManager cancelDiscoveryPrinter];
    _resultMessage = STR_SUCCEEDED;
}

/// Sample for getting discovered printer list
+ (NSArray *)getFoundPrinterSample {
    return [_printerManager getFoundPrinter];
}

/// Get SDK Version
+ (NSString *)getVersionSample {
    return [_printerManager getVersion];
}

+ (NSInteger)get_sendTimeoutSample
{
    NSInteger timeout = _printerManager.sendTimeout;

    return timeout;
}

+ (NSInteger)set_sendTimeoutSample:(NSInteger)time
{
    _printerManager.sendTimeout = time;

    if (_printerManager.sendTimeout == time) {
        _resultMessage = @"Succeeded";
    } else {
        _resultMessage = @"sendTimeout is rounded";
    }
    return _printerManager.sendTimeout;
}

+ (NSInteger)get_receiveTimeoutSample
{
    NSInteger timeout = _printerManager.receiveTimeout;

    return timeout;
}

+ (NSInteger)set_receiveTimeoutSample:(NSInteger)time
{
    _printerManager.receiveTimeout = time;

    if (_printerManager.receiveTimeout == time) {
        _resultMessage = @"Succeeded";
    } else {
        _resultMessage = @"receiveTimeout is rounded";
    }
    return _printerManager.receiveTimeout;
}

+ (NSInteger)get_internationalCharacterSample
{
    NSInteger internationalCharacter = _printerManager.internationalCharacter;
    return internationalCharacter;
}

+ (NSInteger)set_internationalCharacterSample:(NSInteger)internationalCharacter
{
    _printerManager.internationalCharacter = internationalCharacter;

    if (_printerManager.internationalCharacter == internationalCharacter) {
        _resultMessage = @"Succeeded";
    } else {
        _resultMessage = @"Fail to set internationalCharacter";
    }
    return _printerManager.internationalCharacter;
}

+ (NSInteger)get_codePageSample
{
    NSInteger codePage = _printerManager.codePage;
    return codePage;
}

+ (NSInteger)set_codePageSample:(NSInteger)codePage
{
    _printerManager.codePage = codePage;

    if (_printerManager.codePage == codePage) {
        _resultMessage = @"Succeeded";
    } else {
        _resultMessage = @"Faile to set codePage";
    }
    return _printerManager.codePage;
}

+ (NSInteger)get_socketKeepingTimeSample
{
    NSInteger socketKeepingTime = _printerManager.socketKeepingTime;

    return socketKeepingTime;
}

+ (NSInteger)set_socketKeepingTimeSample:(NSInteger)time
{
    _printerManager.socketKeepingTime = time;

    if (_printerManager.socketKeepingTime == time) {
        _resultMessage = @"Succeeded";
    } else {
        _resultMessage = @"socketKeepingTime is rounded";
    }
    return _printerManager.socketKeepingTime;
}

+ (NSString *)getResultMessage {
    return _resultMessage;
}

/// Set a SIIPrinterManagerDelegate instance as delegate referred to ViewController
+ (void)setDelegate:(ViewController *)view {
    _printerManager.delegate = (id <SIIPrinterManagerDelegate>)view;
}

/// Set a SIIPrinterManagerDelegate instance to nil to disable delegate
+ (void)disableDelegate {
    _printerManager.delegate = nil;
}

/// Sample using object selection and template showing #1
+ (BOOL)displaySample_total:(NSInteger)total {
    _resultMessage = STR_SUCCEEDED;
    
    // Change the display content to match the language of the device.
    NSInteger templateID = 119;
    NSInteger rate = 100;
    NSString *currencyUnit = @"$";
    NSString *title = @"Total";
    NSString *strTotal = @"";
    
    NSString *lang = [[NSLocale preferredLanguages] objectAtIndex:0];
    if ([lang hasPrefix:@"ja"] == YES) {
        //Language used: Japanese
        _printerManager.internationalCharacter = SII_PM_COUNTRY_JAPAN;
        _printerManager.codePage =  SII_PM_CODE_PAGE_KATAKANA;
        
        currencyUnit = @"¥";
        rate = 1;
        title = @"合計";
        templateID = 120;
        
        strTotal = [NSString stringWithFormat:@"%@%ld", currencyUnit, total/rate];
    } else {
        //Language used: English
        _printerManager.internationalCharacter = SII_PM_COUNTRY_USA;
        _printerManager.codePage = SII_PM_CODE_PAGE_1252;
        
        strTotal = [NSString stringWithFormat:@"%@%ld.%ld", currencyUnit, total/rate, total%rate];
    }
    
    @try {
        // Select template (ID=119 : for List Up(En)) with Slide 80
        // Select template (ID=120 : for List Up(Jp)) with Slide 80
        [_printerManager selectTemplate:templateID slideID:80];
        
        // Select Text area 0
        [_printerManager selectTemplateTextObject:0];
        [_printerManager setTemplateTextData:title];

        // Select Text area 1
        [_printerManager selectTemplateTextObject:1];
        [_printerManager setTemplateTextData:strTotal];
        
        // Display
        [_printerManager showTemplate:0];
        [NSThread sleepForTimeInterval:0.3f];
    } @catch (SIIPrinterException *e) {
        _resultMessage = [self getErrorMessage:e.errorCode];
        return NO;
    }
    return YES;
}

/// Sample using object selection and template showing #2
+ (BOOL)displaySample_detail:(NSInteger)subTotal itemName:(NSString *)itemName price: (NSInteger) price {
    _resultMessage = STR_SUCCEEDED;
    
    // Change the display content to match the language of the device.
    NSInteger rate = 100;
    NSString *currencyUnit = @"$";
    NSString *strSubTotal = @"";
    NSString *strPrice = @"";
    
    NSString *lang = [[NSLocale preferredLanguages] objectAtIndex:0];
    if ([lang hasPrefix:@"ja"] == YES) {
        //Language used: Japanese
        _printerManager.internationalCharacter = SII_PM_COUNTRY_JAPAN;
        _printerManager.codePage =  SII_PM_CODE_PAGE_KATAKANA;
        
        currencyUnit = @"¥";
        rate = 1;
        
        strSubTotal = [NSString stringWithFormat:@"%@%ld", currencyUnit, subTotal/rate];
        strPrice = [NSString stringWithFormat:@"%@%ld", currencyUnit, price/rate];
    } else {
        //Language used: English
        _printerManager.internationalCharacter = SII_PM_COUNTRY_USA;
        _printerManager.codePage = SII_PM_CODE_PAGE_1252;
        
        strSubTotal = [NSString stringWithFormat:@"%@%ld.%ld", currencyUnit, subTotal/rate, subTotal%rate];
        strPrice = [NSString stringWithFormat:@"%@%ld.%ld", currencyUnit, price/rate, price%rate];
    }
    @try {
        // Select Text area 1
        [_printerManager selectTemplateTextObject:1];
        [_printerManager setTemplateTextData:strSubTotal];

        // Select Text area 6
        [_printerManager selectTemplateTextObject:6];
        [_printerManager setTemplateTextData:itemName];
        
        // Select Text area 7
        [_printerManager selectTemplateTextObject:7];
        [_printerManager setTemplateTextData:strPrice];
        
        // Display
        [_printerManager showTemplate:0];
        [NSThread sleepForTimeInterval:0.3f];
    } @catch (SIIPrinterException *e) {
        _resultMessage = [self getErrorMessage:e.errorCode];
        return NO;
    }
    return YES;
}

/// Sample using object selection and template showing #3
+ (BOOL)displaySample_payment:(NSInteger)total paid:(NSInteger)paid change: (NSInteger) change {
    _resultMessage = STR_SUCCEEDED;
    
    // Change the display content to match the language of the device.
    NSInteger templateID = 123;
    NSInteger slideID = 82;
    NSInteger rate = 100;
    NSString *currencyUnit = @"$";
    NSString *strTotal = @"";
    NSString *strPaid = @"";
    NSString *strChange = @"";
    
    NSString *lang = [[NSLocale preferredLanguages] objectAtIndex:0];
    if ([lang hasPrefix:@"ja"] == YES) {
        //Language used: Japanese
        _printerManager.internationalCharacter = SII_PM_COUNTRY_JAPAN;
        _printerManager.codePage =  SII_PM_CODE_PAGE_KATAKANA;
        
        currencyUnit = @"¥";
        rate = 1;
        templateID = 124;
        slideID = 83;
        
        strTotal = [NSString stringWithFormat:@"%@%ld", currencyUnit, total/rate];
        strPaid = [NSString stringWithFormat:@"%@%ld", currencyUnit, paid/rate];
        strChange = [NSString stringWithFormat:@"%@%ld", currencyUnit, change/rate];
        
    } else {
        //Language used: English
        _printerManager.internationalCharacter = SII_PM_COUNTRY_USA;
        _printerManager.codePage = SII_PM_CODE_PAGE_1252;
        
        strTotal = [NSString stringWithFormat:@"%@%ld.%ld", currencyUnit, total/rate, total%rate];
        strPaid = [NSString stringWithFormat:@"%@%ld.%ld", currencyUnit, paid/rate, paid%rate];
        strChange = [NSString stringWithFormat:@"%@%ld.%ld", currencyUnit, change/rate, change%rate];
    }
    @try {
        // Select template (ID=123 : for 3 lines(En)) with Slide 82
        // Select template (ID=124 : for 3 lines(Jp)) with Slide 83
        [_printerManager selectTemplate:templateID slideID:slideID];
        
        // Select Text area 3
        [_printerManager selectTemplateTextObject:3];
        [_printerManager setTemplateTextData:strTotal];

        // Select Text area 4
        [_printerManager selectTemplateTextObject:4];
        [_printerManager setTemplateTextData:strPaid];
        
        // Select Text area 5
        [_printerManager selectTemplateTextObject:5];
        [_printerManager setTemplateTextData:strChange];
        
        // Display
        [_printerManager showTemplate:0];
        [NSThread sleepForTimeInterval:3.0f];
    } @catch (SIIPrinterException *e) {
        _resultMessage = [self getErrorMessage:e.errorCode];
        return NO;
    }
    return YES;
}

/// Sample of putting the display on standby
+ (BOOL)displaySample_standby {
    _resultMessage = STR_SUCCEEDED;
    @try {
        [_printerManager enterStandbyMode];
    } @catch (SIIPrinterException *e) {
        _resultMessage = [self getErrorMessage:e.errorCode];
        return NO;
    }
    return YES;
}

/// Sample of getting printer response
+ (BOOL)response_request {
    @try {
        // When getting response success, response code(0x80) will be saved in val.
        UInt8 param[1] = { 0x00 };
        NSInteger val[1];
        [_printerManager getPrinterResponse:SII_PM_PRINTER_RESPONSE_REQUEST param:[NSData dataWithBytes:param length:sizeof(param)] response:val];
        return YES;
    }
    @catch (SIIPrinterException *e) {
        return NO;
    }
}

+ (NSString *)getErrorMessage:(NSInteger)errorCode {
    switch (errorCode) {
        case SII_PM_ERROR_ACCESS_DENIED:
            return @"Exception:ACCESS_DENIED";
        case SII_PM_ERROR_SHARING_VIOLATION:
            return @"Exception:SHARING_VIOLATION";
        case SII_PM_ERROR_PORT_NOT_OPENED:
            return @"Exception:PORT_NOT_OPENED";
        case SII_PM_ERROR_DEVICE_NOT_CONNECTED:
            return @"Exception:DEVICE_NOT_CONNECTED";
        case SII_PM_ERROR_OFFLINE:
            return @"Exception:OFFLINE";
        case SII_PM_ERROR_EXTERNAL_DEVICE_NOT_CONNECTED:
            return @"Exception:EXTERNAL_DEVICE_NOT_CONNECTED";
        case SII_PM_ERROR_DEVICE_INITIALIZE_FAILED:
            return @"Exception:DEVICE_INITIALIZE_FAILED";
        case SII_PM_ERROR_DATA_SIZE_ZERO:
            return @"Exception:DATA_SIZE_ZERO";
        case SII_PM_ERROR_OVER_MAX_DATA_SIZE:
            return @"Exception:OVER_MAX_DATA_SIZE";
        case SII_PM_ERROR_DATA_SIZE_INVALID:
            return @"Exception:DATA_SIZE_INVALID";
        case SII_PM_ERROR_ENCODE_FAILED:
            return @"Exception:ENCODE_FAILED";
        case SII_PM_ERROR_TIMEOUT:
            return @"Exception:TIMEOUT";
        case SII_PM_ERROR_FILE_NOT_FOUND:
            return @"Exception:FILE_NOT_FOUND";
        case SII_PM_ERROR_FILE_USED:
            return @"Exception:FILE_USED";
        case SII_PM_ERROR_FILE_INVALID:
            return @"Exception:FILE_INVALID";
        case SII_PM_ERROR_LOW_MEMORY:
            return @"Exception:LOW_MEMORY";
        case SII_PM_ERROR_OVER_MAX_IMAGE:
            return @"Exception:OVER_MAX_IMAGE";
        case SII_PM_ERROR_LOGO_NOT_DEFINED:
            return @"Exception:LOGO_NOT_DEFINED";
        case SII_PM_ERROR_LOW_USER_AREA:
            return @"Exception:LOW_USER_AREA";
        case SII_PM_ERROR_LOW_EXTERNAL_RAM:
            return @"Exception:LOW_EXTERNAL_RAM";
        case SII_PM_ERROR_NOT_REGISTERD:
            return @"Exception:NOT_REGISTERD";
        case SII_PM_ERROR_NOT_UNREGISTERD:
            return @"Exception:NOT_UNREGISTERD";
        case SII_PM_ERROR_INVALID_NO:
            return @"Exception:INVALID_NO";
        case SII_PM_ERROR_OVER_STYLE_NUM:
            return @"Exception:OVER_STYLE_NUM";
        case SII_PM_ERROR_INVALID_DATA:
            return @"Exception:INVALID_DATA";
        case SII_PM_ERROR_PAGE_MODE_SPECIFIED:
            return @"Exception:PAGE_MODE_SPECIFIED";
        case SII_PM_ERROR_PAGE_MODE_NOT_SPECIFIED:
            return @"Exception:PAGE_MODE_NOT_SPECIFIED";
        case SII_PM_ERROR_LABEL_FILE_NOT_SELECTED:
            return @"Exception:LABEL_FILE_NOT_SELECTED";
        case SII_PM_ERROR_GET_LABEL_IMAGE:
            return @"Exception:GET_LABEL_IMAGE";
        case SII_PM_ERROR_INVALID_PARAM:
            return @"Exception:INVALID_PARAM";
        default:
            return @"Exception:Unknown error";
    }
}
@end
