//
//  PinpadHelper.m
//  MyBluetoothTest
//
//  Created by Emmanuel Adeyemi on 11/11/15.
//  Copyright © 2015 Emmanuel Adeyemi. All rights reserved.
//

#import "PinpadHelper.h"

@implementation PinpadHelper{
    dispatch_semaphore_t fd_sema;
}

#define OP_NONE 0

+(void)initScreen:(DTDevices *)dtdev{
    
//    if(dtdevice.connstate==CONN_CONNECTED)
//    {
////        [dtdevice ]
//        [dtdevice scInit:SLOT_MAIN error:nil];
//        NSLog(@"This is to be called to initalised screen");
//    }
    
    if([dtdev getSupportedFeature:FEAT_PIN_ENTRY error:nil])
    {
        if(![dtdev uiStopAnimation:ANIM_ALL error:nil])
            return;
        if(![dtdev uiFillRectangle:0 topLeftY:0 width:0 height:0 color:[UIColor blackColor] error:nil])
            return;
        
        if(dtdev.uiDisplayHeight<64)
        {
            // [dtdev uiDrawText:@"\x01Insert smartcard\nor swipe magnetic\ncard" topLeftX:0 topLeftY:0 font:FONT_6X8 error:nil];
            [dtdev uiDrawText:@"    PINPAD\n   CONNECTED" topLeftX:0 topLeftY:0 font:FONT_8X16 error:nil];
        }else
        {
            [dtdev uiDrawText:@"\x01Use Smart,\nMagnetic " topLeftX:25 topLeftY:3 font:FONT_6X8 error:nil];
            //magnetic card
            [dtdev uiStartAnimation:5 topLeftX:99 topLeftY:0 animated:TRUE error:nil];
            //smartcard
            [dtdev uiStartAnimation:4 topLeftX:0 topLeftY:0 animated:TRUE error:nil];
            [dtdev uiDisplayImage:38 topLeftY:30 image:[UIImage imageNamed:@"paypass_logo.bmp"] error:nil];
        }
    }
}

/**
 *This is used to check if a smart card is present in the smartcard slot
 **/
+(BOOL)isCardInserted:(DTDevices *)dtdevice{
    
    if([dtdevice scIsCardPresent:SLOT_MAIN error:nil]){
        return YES;
    }
    
    return NO;
}

+(void)showValidPin:(DTDevices *)dtdevice{
    
    [dtdevice uiDrawText:[NSString stringWithFormat:@"\x01       %@",@"PIN ENTRY STATUS"] topLeftX:0 topLeftY:0 font:FONT_4X6 error:nil];
    [dtdevice uiDrawText:[NSString stringWithFormat:@"\x01   %@",@"VALID PIN"] topLeftX:0 topLeftY:7 font:FONT_8X16 error:nil];
    
    [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:1]];
    
    [self sleepFor:2.0f];
    
}

+(void)showInvalidPin:(DTDevices *)dtdevice{
    
    [dtdevice uiDrawText:[NSString stringWithFormat:@"\x01    %@",@"PIN ENTRY STATUS"] topLeftX:0 topLeftY:0 font:FONT_4X6 error:nil];
    [dtdevice uiDrawText:[NSString stringWithFormat:@"\x01  %@",@"INVALID PIN"] topLeftX:0 topLeftY:7 font:FONT_8X16 error:nil];
    [self sleepFor:2.0f];
    [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:1]];
    
}

+(void)clearScreen:(DTDevices *)dtdevice{
    
    if(dtdevice.connstate == CONN_CONNECTED){
        [dtdevice uiStopAnimation:-1 error:nil];
        [dtdevice uiFillRectangle:0 topLeftY:0 width:0 height:0 color:[UIColor blackColor] error:nil];
    }
}

+(int)presentCard:(DTDevices *)dtdev{
    
    [PinpadHelper removeCard:dtdev];
    
    [self clearScreen:dtdev];
    
    [dtdev scInit:SLOT_MAIN error:nil];
    
    [dtdev uiDrawText:[NSString stringWithFormat:@"\x01%@",@"\x01    PLEASE \n  INSERT CARD"] topLeftX:0 topLeftY:0 font:FONT_8X16 error:nil];
    
//    [PinpadHelper showMessage:dtdev message:@"Insert Smart Card"];
    char* key;
    
    char charact = [PinpadHelper readKey:dtdev character:key];
    
    int counter = 0;
    
    do{
        char charact = [PinpadHelper readKey:dtdev character:key];
        
        // This is used in sleeping the thread for 1second
        usleep(1000);
        
        NSString *keyString = [NSString stringWithUTF8String:&charact];
        
        if([keyString isEqualToString:@"C"]){
            NSLog(@"They are equal");
        }
        
        counter++;
        
        if(counter == 70)
            return -1;
        
    }while(![PinpadHelper isCardInserted:dtdev]);
    
    return 0;
}

+(int)presentCard:(DTDevices *)dtdev quit:(int *)quit{
    
    [PinpadHelper removeCard:dtdev];
    
    [self clearScreen:dtdev];
    
    [dtdev scInit:SLOT_MAIN error:nil];
    
    [dtdev uiDrawText:[NSString stringWithFormat:@"\x01%@",@"\x01     PLEASE \n  INSERT CARD"] topLeftX:0 topLeftY:0 font:FONT_8X16 error:nil];
    
    //    [PinpadHelper showMessage:dtdev message:@"Insert Smart Card"];
    char* key;
    
//    char charact = [PinpadHelper readKey:dtdev character:key];
    
    int counter = 0;
    
    do{
        char charact = [PinpadHelper readKey:dtdev character:key];
        
        // This is used in sleeping the thread for 1second
        
        NSString *keyString = [NSString stringWithUTF8String:&charact];
        
        if([keyString isEqualToString:@"C"]){
            NSLog(@"They are equal");
        }
        
        counter++;
        
        if(*quit == 10)
            return -1;
        
        
        if(counter == 70)
            return -1;
        
    }while(![PinpadHelper isCardInserted:dtdev]);
    
    return 0;
    
}

+(BOOL) readKey: (DTDevices *) dtdev
     character : (char *) character{
    
    BOOL status = [dtdev ppadKeyboardControl:true error:nil];
    
    if(status){
        status = [dtdev ppadReadKey:character error:nil];
    }
    
    return status;
}

/**
 *
 * This called when we want a user to remove his/her smart card from the card slot
 * @dtdevice - This is reference to the PINPAD object
 *
 */
+(void)removeCard:(DTDevices *)dtdevice{
    
    [dtdevice scInit:SLOT_MAIN error:nil];

    if(dtdevice.connstate == CONN_CONNECTED){
        
        // This is used initializing the card
        
        if(![self isCardInserted:dtdevice]){
            return;
        }
        
        [self clearScreen:dtdevice];
        [dtdevice uiDrawText:[NSString stringWithFormat:@"\x01   %@",@"REMOVE CARD"] topLeftX:0 topLeftY:0 font:FONT_8X16 error:nil];
        
        do{
            // This continues beeping until the card is removed from the PINPAD
            [self beepAttention:dtdevice];
            
        }while([self isCardInserted:dtdevice]);
    }
    
}

//
// This section is for displaying some default messages on the screen
+(void)showSuccessful:(DTDevices *)dtdevice{
    
    [self clearScreen:dtdevice];
    [dtdevice uiDrawText:[NSString stringWithFormat:@"\x01  TRANSACTION \n   SUCCESSFUL"] topLeftX:0 topLeftY:0 font:FONT_8X16 error:nil];
    [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:2]];
    // [self initScreen:dtdevice];
}

//
+(void)showCanceled:(DTDevices *)dtdevice{
    [self clearScreen:dtdevice];
    [dtdevice uiDrawText:[NSString stringWithFormat:@"\x01  TRANSACTION \n   CANCELLED"] topLeftX:0 topLeftY:0 font:FONT_8X16 error:nil];
    [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:1.5]];
    [self initScreen:dtdevice];
}

//+(void)beepSuccess:(DTDevices *)dtdevice{
//    
//    //F,I,F,I,F,I : F -frequency of sound, I- Interval
//    int beepArray[] = {2000,400,2000,400};
//
//    int size = sizeof(beepArray);
//    
//    [dtdevice playSound:100 beepData:beepArray length:size error:nil];
//}
//
//+(void)beepFailure:(DTDevices *)dtdevice{
//    int beepArray[] = {5000,400,5000,400,5000,400};
//    
//    int size = sizeof(beepArray);
//    
//    [dtdevice playSound:100 beepData:beepArray length:size error:nil];
//}
//
+(void)beepAttention:(DTDevices *)dtdevice{
    //F,I,F,I,F,I : F -frequency of sound, I- Interval
    int beepArray[] = {2000,250};
    
    int size = sizeof(beepArray);
    
    [dtdevice playSound:100 beepData:beepArray length:size error:nil];
}
//
//// This section is for displaying some default messages on the screen
//+(void)showSuccessful:(DTDevices *)dtdevice{
//    
//    [dtdevice uiDrawText:[NSString stringWithFormat:@"\x01%@",@"TRANSACTION SUCCESSFUL"] topLeftX:0 topLeftY:0 font:FONT_8X16 error:nil];
//}
//
//+(void)showAborted:(DTDevices *)dtdevice{
//    [dtdevice uiDrawText:[NSString stringWithFormat:@"\x01%@",@"TRANSACTION ABORTED"] topLeftX:0 topLeftY:0 font:FONT_8X16 error:nil];
//}
//
//+(void)showBusy:(DTDevices *)dtdevice{
//    [dtdevice uiDrawText:[NSString stringWithFormat:@"\x01%@",@"PLEASE WAIT"] topLeftX:0 topLeftY:0 font:FONT_8X16 error:nil];
//    [dtdevice uiDrawText:[NSString stringWithFormat:@"\x01%@",@"Performing Operation"] topLeftX:5 topLeftY:17 font:FONT_6X8 error:nil];
//}
//
//+(void)showCanceled:(DTDevices *)dtdevice{
//    [dtdevice uiDrawText:[NSString stringWithFormat:@"\x01%@",@"TRANSACTION CANCELLED"] topLeftX:0 topLeftY:0 font:FONT_8X16 error:nil];
//}
//
//+(void)showDenied:(DTDevices *)dtdevice{
//    [dtdevice uiDrawText:[NSString stringWithFormat:@"\x01%@",@"TRANSACTION DENIED"] topLeftX:0 topLeftY:0 font:FONT_8X16 error:nil];
//}
//
//+(void)showInvalidPin:(DTDevices *)dtdevice{
//    [dtdevice uiDrawText:[NSString stringWithFormat:@"\x01%@",@"INVALID PIN"] topLeftX:0 topLeftY:0 font:FONT_8X16 error:nil];
//    [dtdevice uiDrawText:[NSString stringWithFormat:@"\x01%@",@"Please try again"] topLeftX:2 topLeftY:17 font:FONT_6X8 error:nil];
//}
//
//+(void)showValidPin:(DTDevices *)dtdevice{
//    [dtdevice uiDrawText:[NSString stringWithFormat:@"\x01%@",@"VALID PIN"] topLeftX:0 topLeftY:0 font:FONT_8X16 error:nil];
//}
//
+(void)showMessage:(DTDevices *)dtdevice message:(NSString *)message{
    
    [self clearScreen:dtdevice];
    [dtdevice uiDrawText:[NSString stringWithFormat:@"\x01%@",message] topLeftX:0 topLeftY:0 font:FONT_8X16 error:nil];
    [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:1]];
    [self initScreen:dtdevice];
}
//
//+(void)initScreen:(DTDevices *)dtdevice{
//    // This is called when the screen is to be re-initialised
//}
//
///**
// * This allows for pin entry on pinpad with a given amount
// * This method blocks until the PIN is entered or the timeout is reached
// **/
//+(BOOL)enterPinSync:(DTDevices *)dtdevice amount:(NSString *)amount{
////    [self  showMessage:dtdevice message: [NSString stringWithFormat: @"Amount: %@",amount]];
//    NSError *err = [[NSError alloc] init];
//    return [dtdevice ppadPINEntry:0 startY:0 timeout:60 echoChar:'*'
//                   message:[NSString stringWithFormat:@"AMOUNT: %@ \nENTER PIN: ",amount] error:&err];
//}
//

+(void)enterPinASync:(DTDevices *)dtdevice
              amount:(NSString *)amount{
    
    // This creates the semaphore
//    dispatch_semaphore_t fd_sema = dispatch_semaphore_create(0);
//    
    NSError *error;
    
    [dtdevice ppadStartPINEntry:0 startY:1 timeout:70 echoChar:'*'
                        message:[NSString stringWithFormat:@"AMT: N%@ \nEnter PIN:",amount] error:&error];

//    dispatch_semaphore_wait(fd_sema, DISPATCH_TIME_FOREVER);
//    dispatch_release(fd_sema);
    
   // return ;
}

+(void) sleepFor:(float) second{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        //Here your non-main thread.
        [NSThread sleepForTimeInterval:second];
    });
}

+(void)showWaiting:(DTDevices *)dtdev{
    
    [self clearScreen:dtdev];
    [dtdev uiDrawText:[NSString stringWithFormat:@"\x01          %@",@"PROCESSING"] topLeftX:0 topLeftY:0 font:FONT_4X6 error:nil];
    [dtdev uiDrawText:[NSString stringWithFormat:@"\x01  %@",@"PLEASE WAIT"] topLeftX:0 topLeftY:8 font:FONT_8X16 error:nil];
//    [self initScreen:dtdev];
}

/**
 * This is called to disconnect the pinpad
 */
+(void)disconnectPinpad : (DTDevices*) dtdev{
    [dtdev disconnect];
}

+(NSString*)getDeviceSerial:(DTDevices *)dtdev{
    NSString *serial = [dtdev serialNumber];
    NSLog(@"The serial is %@", serial);
    
    return serial;
}

@end
