#import "PaymentViewController.h"
#import <CoreBluetooth/CoreBluetooth.h>
#import <ExternalAccessory/ExternalAccessory.h>

@interface PaymentViewController()<UITabBarControllerDelegate>

@property (weak, nonatomic) IBOutlet UILabel *statusLabel;
@property (weak, nonatomic) IBOutlet UILabel *summaryLabel;
@property (weak, nonatomic) IBOutlet UIView *signatureView;
@property (weak, nonatomic) IBOutlet UIView *topView;
@property (weak, nonatomic) IBOutlet UITextField *amountView;
@property (weak, nonatomic) IBOutlet UIButton *confirmButton;
@property (weak, nonatomic) IBOutlet UIButton *submitSignatureButton;
@property (weak, nonatomic) IBOutlet SignatureCanvas *SignatureCanvas;
@property (weak, nonatomic) IBOutlet UIButton *connectIcon;
@property (weak, nonatomic) IBOutlet UIView *mainView;
@property (weak, nonatomic) IBOutlet UISwitch *debitCheckbox;

@property (weak, nonatomic) IBOutlet UIButton *selectTaxtButton;
@property (weak, nonatomic) IBOutlet UIButton *selectTipButton;
@property (weak, nonatomic) IBOutlet UIButton *customTipButton;
@property (weak, nonatomic) IBOutlet UIButton *clearTipButton;
@property (weak, nonatomic) IBOutlet UIButton *okTipButton;
@property (weak, nonatomic) IBOutlet UIView *tipTaxView;
@property (weak, nonatomic) IBOutlet UILabel *tipAndTaxLabel;
@property (weak, nonatomic) IBOutlet UISwitch *tipAndTaxSwitch;
@property (weak, nonatomic) IBOutlet UILabel *bypassSurchargeLabel;
@property (weak, nonatomic) IBOutlet UISwitch *bypassSurchargeSwitch;

@property (weak, nonatomic) IBOutlet UISwitch *customFieldSwitch;
@property (weak, nonatomic) IBOutlet UILabel *customFieldLabel;
@property (weak, nonatomic) IBOutlet UIView *customFieldView;
@property (weak, nonatomic) IBOutlet UIButton *clearButton;
@property (weak, nonatomic) IBOutlet UIButton *okButton;
@property (weak, nonatomic) IBOutlet UITextField *nameOne;
@property (weak, nonatomic) IBOutlet UITextField *valueOne;
@property (weak, nonatomic) IBOutlet UITextField *nameTwo;
@property (weak, nonatomic) IBOutlet UITextField *valueTwo;
@property (weak, nonatomic) IBOutlet UITextField *nameThree;
@property (weak, nonatomic) IBOutlet UITextField *valueThree;
@property (weak, nonatomic) IBOutlet UITextField *nameFour;
@property (weak, nonatomic) IBOutlet UITextField *valueFour;
@end


@implementation PaymentViewController
{
    UIStoryboard *storyboard;
    ViewType viewType;
    UIColor* color;
    UIActionSheet *bluetoothSelection;
    CoreSettings* coreSettings;
    NSString* nfcEnabledSupported;
    BOOL inTransaction;
    CardDetailsViewController* cardDetails;
    NSMutableDictionary* tipMap;
    NSMutableDictionary* taxMap;
    UIActionSheet * actionSheetTaxList;
    UIActionSheet * actionSheetTipList;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tabBarController.delegate = self;
    _signatureView.hidden = YES;
    _customFieldView.hidden = YES;
    _tipTaxView.hidden = YES;
    _tipAndTaxSwitch.hidden = YES;
    _tipAndTaxLabel.hidden = YES;
    _bypassSurchargeSwitch.hidden = YES;
    _bypassSurchargeLabel.hidden = YES;
    storyboard = [UIStoryboard storyboardWithName:@"Mainview" bundle:nil];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Settings" style:UIBarButtonItemStylePlain target:self action:@selector(openSettings)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
    color = UIColorFromRGB(0xC11D03);
    NSString *restorationId = self.restorationIdentifier;
    if([restorationId isEqualToString:@"saleViewController"]){
        viewType = SALE;
        [_summaryLabel setText:@"SALE"];
        [_confirmButton setTitle:@"SALE" forState:UIControlStateNormal];
        [self setTheme];
    } else {
        viewType = REFUND;
        [_summaryLabel setText:@"REFUND"];
        [_confirmButton setTitle:@"REFUND" forState:UIControlStateNormal];
        [self setTheme];
    }
    
    NSString* terminalId = [Util getFromSettings:@"terminalId"];
    NSString* secret = [Util getFromSettings:@"secret"];
    if([RestConnector isPayconexSDK]){
        terminalId = @"220614969941";
        secret = @"0e8d38a08f2d4919a5a27ec83a6e8d76";
        [self checkPayconexSettings];
    }
   
    NSString* mode = [Util getFromSettings:@"mode"];
    if(mode != nil){
        [self setMode];
        [[WTPSTerminal singleton] setMode:[Util coreMode:mode]];
    }
    [[WTPSTerminal singleton] initWithConfiguration:terminalId withSecret:secret];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]
                                   initWithTarget:self
                                   action:@selector(dismissKeyboard)];
    
    [self.view addGestureRecognizer:tap];
    [self.amountView setReturnKeyType:UIReturnKeyDone];
    [self.amountView setDelegate:self];
    
    if([[WTPSTerminal singleton] getDevice] != NODEVICE){
        [_connectIcon setImage:[UIImage imageNamed:@"connected.png"] forState:UIControlStateNormal];
    }
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

- (IBAction)clearButtonHandle:(id)sender {
    _nameOne.text = @"";
    _valueOne.text = @"";
    _nameTwo.text = @"";
    _valueTwo.text = @"";
    _nameThree.text = @"";
    _valueThree.text = @"";
    _nameFour.text = @"";
    _valueFour.text = @"";
}
- (IBAction)okButtonHandle:(id)sender {
    [UIView transitionWithView:_customFieldView
                      duration:0.5
                       options:UIViewAnimationOptionTransitionCrossDissolve
                    animations:^{
        _customFieldView.hidden = YES;
    }
                    completion:NULL];
    
    _customFieldLabel.text =_nameOne.text.length != 0 ? @"Custom fields added" : @"Add custom fields";
    [_customFieldSwitch setOn:_nameOne.text.length != 0];
}
- (IBAction)customFieldSwitchHandle:(id)sender {
    CATransition *animation = [CATransition animation];
    animation.duration = 0.5;
    animation.type = kCATransitionMoveIn;
    animation.subtype = kCATransitionFromLeft;
    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    [_customFieldView.layer addAnimation:animation forKey:@"changeTextTransition"];
    
    _customFieldView.hidden = NO;
}

- (void)calculateAllAmounts{
    BOOL taxOrTipAdded = ![_selectTaxtButton.currentTitle isEqualToString:@"Select tax"] || ![_selectTipButton.currentTitle isEqualToString:@"Select tip"] || ![_customTipButton.currentTitle isEqualToString:@"Custom tip"];
    [_tipAndTaxSwitch setOn:taxOrTipAdded];
    NSString* message = @"Tips or taxes added";
    if(taxOrTipAdded){
        if(self.amountView.text.length <= 0 || [[[self getAmount] stringValue] isEqualToString:@"0"]){
            _tipAndTaxLabel.text = @"Add tip and tax";
            [_tipAndTaxSwitch setOn:NO];
            return;
        }
        CoreSale *sale = [[CoreSale alloc] init];
        sale.amount = [self getAmount];
        [self addTipOrTaxToSale:sale];
        message = [NSString stringWithFormat:@"Tips or taxes added. Total amount: %@", [[CoreUtil singleton] addUpAllAmounts:sale withCurrency:[[WTPSTerminal singleton] getCurrency]]];
    }
    _tipAndTaxLabel.text = taxOrTipAdded ? message : @"Add tip and tax";
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    NSLog(@"%@", [alertView textFieldAtIndex:0].text);
    if(![[alertView textFieldAtIndex:0].text isEqualToString:@""]){
        [_customTipButton setTitle:[alertView textFieldAtIndex:0].text forState:UIControlStateNormal]; // To set the title
    }
}

- (IBAction)selectTaxButtonHandle:(id)sender {
    [actionSheetTaxList showInView:self.view];
}

- (IBAction)selectTipButtonHandle:(id)sender {
    [actionSheetTipList showInView:self.view];
}

- (IBAction)customTipButtonHandle:(id)sender {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Custom tip amount"
                                                    message:@"Custom tip amount"
                                                   delegate:self
                                          cancelButtonTitle:@"Done"
                                          otherButtonTitles:nil];
    alert.alertViewStyle = UIAlertViewStylePlainTextInput;
    [alert show];
}

- (IBAction)clearTipButtonHandle:(id)sender {
    [_selectTaxtButton setTitle:@"Select tax" forState:UIControlStateNormal];
    [_selectTipButton setTitle:@"Select tip" forState:UIControlStateNormal];
    [_customTipButton setTitle:@"Custom tip" forState:UIControlStateNormal];
}

- (IBAction)okTaxTipButtonHandle:(id)sender {
    [UIView transitionWithView:_tipTaxView
                      duration:0.5
                       options:UIViewAnimationOptionTransitionCrossDissolve
                    animations:^{
        _tipTaxView.hidden = YES;
    }
                    completion:NULL];
    [self calculateAllAmounts];
}

- (IBAction)addTipAndTaxSwitchHandle:(id)sender {
    if(self.amountView.text.length <= 0 || [[[self getAmount] stringValue] isEqualToString:@"0"]){
        [[UiHelper singleton] animateWrongInput:_amountView];
        [_tipAndTaxSwitch setOn:NO];
        return;
    }
    CATransition *animation = [CATransition animation];
    animation.duration = 0.5;
    animation.type = kCATransitionMoveIn;
    animation.subtype = kCATransitionFromLeft;
    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    [_tipTaxView.layer addAnimation:animation forKey:@"changeTextTransition"];
    
    _tipTaxView.hidden = NO;
}

- (IBAction)bypassSurchargeSwitchHandle:(id)sender {
    if(self.amountView.text.length <= 0 || [[[self getAmount] stringValue] isEqualToString:@"0"]){
        [[UiHelper singleton] animateWrongInput:_amountView];
        [_bypassSurchargeSwitch setOn:NO];
        return;
    }
}

- (void) checkPayconexSettings{
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    UITabBarController* tabBarController = (UITabBarController*)appDelegate.window.rootViewController.navigationController;
    NSMutableArray *tbViewControllers = [NSMutableArray arrayWithArray:[tabBarController viewControllers]];
    if([tbViewControllers count] == 5){
        [tbViewControllers removeObjectAtIndex:4];
        [tbViewControllers removeObjectAtIndex:3];
        [tbViewControllers removeObjectAtIndex:1];
        [tabBarController setViewControllers:tbViewControllers];
    }
}

- (NSNumber*)getAmount{
    NSMutableString* amount = [self.amountView.text mutableCopy];
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:
                                  @"[^0-9.]" options:0 error:nil];
    
    [regex replaceMatchesInString:amount options:0 range:NSMakeRange(0, [amount length]) withTemplate:@""];
    return [NSNumber numberWithDouble: [amount doubleValue]];
}

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    if([[textField text] length] - range.length + string.length > 11){
        return NO;
    }
    
    NSString *cleanCentString = [[textField.text componentsSeparatedByCharactersInSet: [[NSCharacterSet decimalDigitCharacterSet] invertedSet]] componentsJoinedByString:@""];
    NSInteger centValue = [cleanCentString intValue];
    NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
    NSNumber *myNumber = [f numberFromString:cleanCentString];
    NSNumber *result;
    
    if (string.length > 0)
    {
        centValue = centValue * 10 + [string intValue];
        double intermediate = [myNumber doubleValue] * 10 +  [[f numberFromString:string] doubleValue];
        result = [[NSNumber alloc] initWithDouble:intermediate];
    }
    else
    {
        centValue = centValue / 10;
        double intermediate = [myNumber doubleValue]/10;
        result = [[NSNumber alloc] initWithDouble:intermediate];
    }
    
    myNumber = result;
    NSLog(@"%ld ++++ %@", (long)centValue, myNumber);
    NSNumber *formatedValue = [[NSNumber alloc] initWithDouble:[myNumber doubleValue]/ 100.0f];
    
    NSNumberFormatter *_currencyFormatter = [[NSNumberFormatter alloc] init];
    [_currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
    if([[WTPSTerminal singleton] getSettings] != nil){
        NSArray *currencyData = getCurrencyData([[WTPSTerminal singleton] getSettings].currency);
        NSString *currencySymbol = [Util findCurrencySymbolByCode:[currencyData objectAtIndex:2]];
        _currencyFormatter.currencySymbol = currencySymbol;
        if ([[currencyData objectAtIndex:1] intValue] == 2){
            formatedValue = [[NSNumber alloc] initWithDouble:[myNumber doubleValue]/ 100.0f];
        } else if ([[currencyData objectAtIndex:1] intValue] == 3){
            formatedValue = [[NSNumber alloc] initWithDouble:[myNumber doubleValue]/ 1000.0f];
        } else {
            formatedValue = [[NSNumber alloc] initWithDouble:[myNumber doubleValue]];
        }
        [self setFractionDigits:_currencyFormatter withNumber:[[currencyData objectAtIndex:1] intValue]];
    } else {
        [self setFractionDigits:_currencyFormatter withNumber:2];
    }
    [_currencyFormatter setRoundingMode:NSNumberFormatterRoundDown];
    textField.text = [_currencyFormatter stringFromNumber:formatedValue];
    [self calculateAllAmounts];
    return NO;
}

- (void) setFractionDigits:(NSNumberFormatter *)currencyFormatter withNumber:(int)digit{
    [currencyFormatter setMaximumFractionDigits:digit];
    [currencyFormatter setMinimumFractionDigits:digit];
}

- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController{
    if((![viewController.restorationIdentifier isEqualToString:@"saleViewControllerNavigation"] && [self.navigationController.restorationIdentifier isEqualToString:@"saleViewControllerNavigation"])
       || (![viewController.restorationIdentifier isEqualToString:@"refundViewControllerNavigation"] && [self.navigationController.restorationIdentifier isEqualToString:@"refundViewControllerNavigation"])){ //
        [[WTPSTerminal singleton] unRegisterCoreAPIDeviceListener:self];
        [[WTPSTerminal singleton] unRegisterCoreAPISaleListener:self];
        [[WTPSTerminal singleton] unRegisterCoreAPIRefundListener:self];
        [[WTPSTerminal singleton] unRegisterCoreAPIReversalListener:self];
        [[WTPSTerminal singleton] unRegisterCoreAPIUpdateListener:self];
        [[WTPSTerminal singleton] unRegisterCoreAPIMessageListener:self];
        [[WTPSTerminal singleton] unRegisterCoreAPIReportingListener:self];
    }
}

- (void)viewWillAppear:(BOOL)animated{
    [[WTPSTerminal singleton] registerCoreAPIDeviceListener:self];
    [[WTPSTerminal singleton] registerCoreAPISaleListener:self];
    [[WTPSTerminal singleton] registerCoreAPIRefundListener:self];
    [[WTPSTerminal singleton] registerCoreAPIReversalListener:self];
    [[WTPSTerminal singleton] registerCoreAPIUpdateListener:self];
    [[WTPSTerminal singleton] registerCoreAPIMessageListener:self];
    [[WTPSTerminal singleton] registerCoreAPIReportingListener:self];
}

- (void)viewDidAppear:(BOOL)animated{
    self.tabBarController.tabBar.tintColor = color;
    [self setMode];
}

- (void) setMode{
    NSString* mode = [Util getFromSettings:@"mode"];
    if(mode != nil){
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:mode style:UIBarButtonItemStylePlain target:self action:nil];
        self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];
        self.navigationItem.rightBarButtonItem.action = @selector(changeUrlDialog);
    }
}

- (void) changeUrlDialog{
    Class theClass = NSClassFromString(@"ChangeHostDialog");
    if (theClass != nil){
        [theClass dialog:self];
    }
}

- (void) setTheme{
    [_amountView setTextColor:color];
    self.navigationController.navigationBar.barTintColor = color;
    self.tabBarController.tabBar.tintColor = color;
}

- (void) openSettings{
    UINavigationController *settings = [storyboard instantiateViewControllerWithIdentifier:@"appSettingsViewControllerNavigation"];
    [self presentViewController:settings animated:YES completion:nil];
}

-(void)dismissKeyboard {
    [_amountView resignFirstResponder];
    [_nameOne resignFirstResponder];
    [_valueOne resignFirstResponder];
    [_nameTwo resignFirstResponder];
    [_valueTwo resignFirstResponder];
    [_nameThree resignFirstResponder];
    [_valueThree resignFirstResponder];
    [_nameFour resignFirstResponder];
    [_valueFour resignFirstResponder];
}

#pragma mark ------------- ActionSheet handle --------------

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (actionSheet.tag == 50) {
        if(buttonIndex != -1){
            NSString *title = [actionSheet buttonTitleAtIndex:buttonIndex];
            DeviceEnum device = 0;
            if([title isEqual: @"BBPosDevice"]){
                [self changeToBBPosdeviceDevice];
                return;
            } else if([title isEqual: @"Bluepad"]){
                device= BLUEPAD;
            } else {
                return;
            }
            [[UiHelper singleton] showLoading:self.view isDeviceSale:NO];
            [[WTPSTerminal singleton] initDevice:device withConnectionType:BLUETOOTH withBluetoothAddress:nil];
        }
    } else if(actionSheet.tag == 110){
        NSString *title = [actionSheet buttonTitleAtIndex:buttonIndex];
        if([title isEqualToString:@"Bluetooth"]){
            NSMutableDictionary *data = [[NSMutableDictionary alloc] init];
            //[data setObject:[NSNumber numberWithBool:YES] forKey:@"enableTips"];
            //[data setObject:[NSNumber numberWithInt:12] forKey:@"tipPreDefinedAmount"];
            //[data setObject:[NSNumber numberWithBool:YES] forKey:@"enableSurcharges"];
            
            CoreCustomTips* customTips = [[CoreCustomTips alloc] init];
            customTips.percentages = [self createTips:@"PERCENTAGE"];
            customTips.amounts = [self createTips:@"FIXED_AMOUNT"];
            //[data setObject:customTips forKey:@"customTips"];
            
            [[WTPSTerminal singleton] initDevice:BBPOSDEVICE withConnectionType:BLUETOOTH withBluetoothAddress:nil withDeviceData:data];
            
            bluetoothSelection = [[UIActionSheet alloc] initWithTitle:@"Bluetooth devices"
                                                             delegate:self
                                                    cancelButtonTitle:@"Cancel"
                                               destructiveButtonTitle:nil
                                                    otherButtonTitles:nil];
            [bluetoothSelection addButtonWithTitle:@"Scanning..."];
            bluetoothSelection.tag = 1010;
            [bluetoothSelection showInView:self.view];
        } else if([title isEqualToString:@"Audio"]){
            [[WTPSTerminal singleton] initDevice:BBPOSDEVICE withConnectionType:AUDIO withBluetoothAddress:nil];
            [[UiHelper singleton] showLoading:self.view isDeviceSale:NO];
        }
    } else if(actionSheet.tag == 90){
        NSString *title = [actionSheet buttonTitleAtIndex:buttonIndex];
        if(![title isEqualToString:@"Cancel"]){
            [[WTPSTerminal singleton] selectBTDevice:(int)buttonIndex -1];
        } else {
            [[WTPSTerminal singleton] selectBTDevice:-1];
        }
        [[UiHelper singleton] showLoading:self.view isDeviceSale:NO];
    } else if(actionSheet.tag == 60){
        if(![[WTPSTerminal singleton] isDelayedAuthEnabled]){
            if(self.amountView.text.length <= 0 || [[[self getAmount] stringValue] isEqualToString:@"0"]){
                [[UiHelper singleton] animateWrongInput:_amountView];
                return;
            }
        }
        switch (buttonIndex) {
            case 0:
                [self doKeyed];
                break;
            case 1:
                [self doApplePay];
                break;
            default:
                break;
        }
    } else if(actionSheet.tag == 70){
        if(buttonIndex != -1){
            [self doSaleNow:buttonIndex];
        }
    } else if(actionSheet.tag == 80){
        [[WTPSTerminal singleton] submitApplication:(int) buttonIndex];
        [[UiHelper singleton] showLoading:self.view isDeviceSale:NO];
    } else if(actionSheet.tag == 10){
        switch (buttonIndex) {
            case 0:{
                [[WTPSTerminal singleton] disconnectDevice];
                [self connectMenu];
            }
                break;
                
            case 1:{
                [[WTPSTerminal singleton] getDeviceInfo];
            }
                break;
            default:
                break;
        }
    }else if(actionSheet.tag == 120){
        NSString *title = [actionSheet buttonTitleAtIndex:buttonIndex];
        [_selectTaxtButton setTitle:title forState:UIControlStateNormal];
    }else if(actionSheet.tag == 130){
        NSString *title = [actionSheet buttonTitleAtIndex:buttonIndex];
        [_selectTipButton setTitle:title forState:UIControlStateNormal];
    }
}

- (NSMutableArray*) createTips:(NSString*) tipType {
    NSMutableArray* tips = [[NSMutableArray alloc] init];
    for(int i=0; i<3; i++) {
        CoreTip* tip = [[CoreTip alloc] init];
        tip.tipType = tipType;
        if ([tipType isEqual:@"PERCENTAGE"]) {
            tip.percentage = [NSNumber numberWithDouble:(3.0 * (i + 1))];
        } else {
            tip.amount = [NSNumber numberWithDouble:(2.0 * (i + 1))];
        }
        [tips addObject:tip];
    }
    return tips;
}

- (void) doSaleNow:(NSInteger)index{
    if(index == 4){
        [self doKeyed];
        return;
    }
    CoreSale *sale =[[CoreSale alloc] init];
    if(![[WTPSTerminal singleton] isDelayedAuthEnabled]){ // if delayed auth enable, amount will be set in onRequestAmount
        sale.amount = [self getAmount];
    }
    
    if (_bypassSurchargeSwitch.hidden == NO) {
        [sale setBypassSurcharge:[NSNumber numberWithBool:[_bypassSurchargeSwitch isOn]]];
    }
    
    switch (index) {
        case 0:
            sale.transactionInputMethod = SWIPE_OR_INSERT;
            break;
        case 1:
            sale.transactionInputMethod = SWIPE;
            break;
        case 2:
            sale.transactionInputMethod = TAP;
            break;
        case 3:
            sale.emvType = QUICK_CHIP;
            break;
        case 5:
            sale.transactionInputMethod = MANUAL_PAN_ENTRY;
            break;
        case 6:
            sale.transactionInputMethod = SWIPE_OR_INSERT_OR_TAP;
            break;
    }
    
    if (RestConnector.isPayconexSDK) {
        [self addCustomFieldsToCoreSale:sale];
    }
    sale.signatureCollection = AUTOMATIC;
    if([_debitCheckbox isOn]){
        sale.debitAccountType = @"SAVINGS";
    }
    // sale.transactionType = PRE_AUTH;
    
    [self addTipOrTaxToSale:sale];
    [[WTPSTerminal singleton] processSale:sale];
    [[UiHelper singleton] showLoading:self.view isDeviceSale:YES];
    inTransaction = YES;
}

- (void)changeToBBPosdeviceDevice{
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC));
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@""
                                                                 delegate:self
                                                        cancelButtonTitle:@"Cancel"
                                                   destructiveButtonTitle:nil
                                                        otherButtonTitles:@"Bluetooth", @"Audio", nil];
        actionSheet.tag = 110;
        [actionSheet showInView:self.view];
    });
}

#pragma mark ------------- Buttons handle --------------

- (IBAction)pinpadIconHandle:(id)sender {
    [self.view endEditing:YES];
    if([[WTPSTerminal singleton] getDevice] != NODEVICE){
        UIActionSheet * actionSheet = [[UIActionSheet alloc] initWithTitle:@"Devices"
                                                                  delegate:self
                                                         cancelButtonTitle:@"Cancel"
                                                    destructiveButtonTitle:nil
                                                         otherButtonTitles:@"Reconnect",@"Get Device Info", nil];
        actionSheet.tag = 10;
        [actionSheet showInView:self.view];
    } else {
        [self connectMenu];
    }
}

- (void) connectMenu{
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC));
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        NSDictionary* devices = [[WTPSTerminal singleton] listSupportedDevices];
        UIActionSheet * actionSheet = [[UIActionSheet alloc] initWithTitle:@"Devices"
                                                                  delegate:self
                                                         cancelButtonTitle:@"Cancel"
                                                    destructiveButtonTitle:nil
                                                         otherButtonTitles:nil];
        for (NSString *device in devices) {
            [actionSheet addButtonWithTitle:device];
        }
        actionSheet.tag = 50;
        [actionSheet showInView:self.view];
    });
}

- (IBAction)confirmHandle:(id)sender {
    if (viewType == SALE){
        [self doSale];
    } else {
        [self doRefund];
    }
}

- (IBAction)submitSignatureHandle:(id)sender {
    if ([_SignatureCanvas checkSignature] == true) {
        [[WTPSTerminal singleton] submitSignature:_SignatureCanvas.signature];
        [_SignatureCanvas clearCanvas:true];
        _signatureView.hidden = YES;
        
        CATransition *animation = [CATransition animation];
        animation.duration = 1.0;
        animation.type = kCATransitionFade;
        animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
        [_mainView.layer addAnimation:animation forKey:@"changeTextTransition"];
        _mainView.hidden = NO;
        [[UiHelper singleton] showLoading:self.view isDeviceSale:NO];
    }else{
        [[UiHelper singleton] showWarning:@"Signature cannot be empty"];
    }
}

- (void) doSale{
    if(![[WTPSTerminal singleton] isDelayedAuthEnabled]){
        if(self.amountView.text.length <= 0 || [[[self getAmount] stringValue] isEqualToString:@"0"]){
            [[UiHelper singleton] animateWrongInput:_amountView];
            return;
        }
    }
    UIActionSheet *actionSheet;
    if([[WTPSTerminal singleton] getDevice] != NODEVICE){
        [self doDevice];
    }else{
        actionSheet = [[UIActionSheet alloc] initWithTitle:@"Sale"
                                                  delegate:self
                                         cancelButtonTitle:@"Cancel"
                                    destructiveButtonTitle:nil
                                         otherButtonTitles:@"Keyed", @"Apple Pay",nil];
        actionSheet.tag = 60;
        [actionSheet showInView:self.view];
    }
}

- (void) doDevice{
    if(nfcEnabledSupported != nil){
        UIActionSheet *actionSheet ;
        NSMutableArray* buttons = [NSMutableArray new];
        [buttons addObject:@"Insert/Swipe"];
        [buttons addObject:@"Swipe"];
        [buttons addObject:@"TAP"];
        [buttons addObject:@"Quick Chip"];
        [buttons addObject:@"Manual Entry No Device"];
        [buttons addObject:@"Manual entry"];
        [buttons addObject:@"Insert/Swipe/TAP"];
        actionSheet = [[UIActionSheet alloc] initWithTitle:@"Sale"
                                                  delegate:self
                                         cancelButtonTitle:nil
                                    destructiveButtonTitle:nil
                                         otherButtonTitles:nil];
        for (NSString *title in buttons){
            [actionSheet addButtonWithTitle:title];
        }
        actionSheet.tag = 70;
        [actionSheet showInView:self.view];
    } else {
        CoreSale *sale =[[CoreSale alloc] init];
        sale.amount = [self getAmount];
        sale.signatureCollection = AUTOMATIC;
        if (RestConnector.isPayconexSDK) {
            [self addCustomFieldsToCoreSale:sale];
        }
        [self addTipOrTaxToSale:sale];
        [[WTPSTerminal singleton] processSale:sale];
        [[UiHelper singleton] showLoading:self.view isDeviceSale:YES];
        inTransaction = YES;
    }
    [self.view endEditing:YES];
}

- (void) addCustomFieldsToCoreSale:(CoreSale*)coreSale{
    CoreCustomField *field;
    NSMutableArray *customFields = nil;
    
    if(self.nameOne.text.length > 0){
        if(self.valueOne.text.length <= 0){
            [[UiHelper singleton] showWarning:@"Please enter value for custom field 1"];
            return;
        }
        
        if(customFields == nil){
            customFields = [[NSMutableArray alloc] init];
        }
        
        field = [[CoreCustomField alloc] init];
        field.name = self.nameOne.text;
        field.value = self.valueOne.text;
        [customFields addObject:field];
    }
    
    if(self.nameTwo.text.length > 0){
        if(self.valueTwo.text.length <= 0){
            [[UiHelper singleton] showWarning:@"Please enter value for custom field 2"];
            return;
        }
        
        if(customFields == nil){
            customFields = [[NSMutableArray alloc] init];
        }
        
        field = [[CoreCustomField alloc] init];
        field.name = self.nameTwo.text;
        field.value = self.valueTwo.text;
        [customFields addObject:field];
    }
    
    if(self.nameThree.text.length > 0){
        if(self.valueThree.text.length <= 0){
            [[UiHelper singleton] showWarning:@"Please enter value for custom field 3"];
            return;
        }
        
        if(customFields == nil){
            customFields = [[NSMutableArray alloc] init];
        }
        
        field = [[CoreCustomField alloc] init];
        field.name = self.nameThree.text;
        field.value = self.valueThree.text;
        [customFields addObject:field];
    }
    
    if(self.nameFour.text.length > 0){
        if(self.valueFour.text.length <= 0){
            [[UiHelper singleton] showWarning:@"Please enter value for custom field 4"];
            return;
        }
        
        if(customFields == nil){
            customFields = [[NSMutableArray alloc] init];
        }
        
        field = [[CoreCustomField alloc] init];
        field.name = self.nameFour.text;
        field.value = self.valueFour.text;
        [customFields addObject:field];
    }
    if(customFields != nil){
        coreSale.customFields = customFields;
    }
}


- (void) doKeyed{
    BOOL isKeyed =  [[WTPSTerminal singleton] getSettings] != nil ? [[[[WTPSTerminal singleton] getSettings].features objectForKey:@"allowKeyed"] boolValue] : NO;
    if(!isKeyed){
        [[UiHelper singleton] showWarning:@"Keyed functionality is not enabled in the selfcare system."];
        return;
    }
    UINavigationController *card= [storyboard instantiateViewControllerWithIdentifier:@"cardDetailsNavigation"];
    cardDetails = [[card viewControllers] objectAtIndex:0];
    cardDetails.amount = [self getAmount];
    cardDetails.cardDetaildViewType = CARD_DETAILS_SALE;
    dispatch_async(dispatch_get_main_queue(), ^ {
        [self presentViewController:card animated:YES completion:nil];
    });
}

- (void)addTipOrTaxToSale:(CoreSale*)coreSale{
    if(![_selectTaxtButton.currentTitle isEqualToString:@"Select tax"]){
        NSString* percentage = _selectTaxtButton.titleLabel.text;
        CoreTax* tax = [taxMap valueForKey:percentage];
        coreSale.tax = tax;
    }
    if(![_selectTipButton.currentTitle isEqualToString:@"Select tip"]){
        NSString* percentage = _selectTipButton.titleLabel.text;
        CoreTip* tip = [tipMap valueForKey:percentage];
        coreSale.tip = tip;
    }
    if(![_customTipButton.currentTitle isEqualToString:@"Custom tip"]){
        if(coreSale.tip == nil){
            NSString* amount = _customTipButton.titleLabel.text;
            CoreTip* tip = [CoreTip new];
            tip.tipType = @"FIXED_AMOUNT";
            tip.amount = [NSNumber numberWithDouble:[amount doubleValue]];
            coreSale.tip = tip;
        }
    }
}

#pragma mark ------------- REFUND --------------

- (void) doRefund{
    if(self.amountView.text.length <= 0 || [[[self getAmount] stringValue] isEqualToString:@"0"]){
        [[UiHelper singleton] animateWrongInput:_amountView];
        return;
    }
    
    [self.view endEditing:YES];
    UINavigationController *card= [storyboard instantiateViewControllerWithIdentifier:@"cardDetailsNavigation"];
    cardDetails = [[card viewControllers] objectAtIndex:0];
    cardDetails.amount = [self getAmount];
    cardDetails.cardDetaildViewType = CARD_DETAILS_REFUND;
    dispatch_async(dispatch_get_main_queue(), ^ {
        [self presentViewController:card animated:YES completion:nil];
    });
}

#pragma mark ------------- APPLE PAY --------------

- (void)doApplePay{
    if([PKPaymentAuthorizationViewController canMakePayments]) {
        // request
        PKPaymentRequest *request = [[PKPaymentRequest alloc] init];
        request.countryCode = @"US";
        request.currencyCode = getCurrencyNameByValue(coreSettings.currency -2 );
        request.supportedNetworks = @[PKPaymentNetworkAmex, PKPaymentNetworkMasterCard, PKPaymentNetworkVisa , PKPaymentNetworkDiscover] ;
        request.merchantCapabilities =  PKMerchantCapability3DS;
        request.merchantIdentifier = @"merchant.com.dominik.test";
        
        // Amount
        PKPaymentSummaryItem *widget1 = [PKPaymentSummaryItem summaryItemWithLabel:@"Widget 1" amount:[NSDecimalNumber decimalNumberWithDecimal:[[self getAmount] decimalValue]]];
        request.paymentSummaryItems = @[widget1];
        
        //View
        PKPaymentAuthorizationViewController *paymentPane = [[PKPaymentAuthorizationViewController alloc] initWithPaymentRequest:request];
        if(paymentPane != nil){
            paymentPane.delegate = self;
            [self presentViewController:paymentPane animated:TRUE completion:nil];
        } else {
            [[UiHelper singleton] toastMessage:@"Apple Pay is not set up."];
        }
    } else {
        [[UiHelper singleton] toastMessage:@"Apple Pay is not supported."];
    }
    [self.view endEditing:YES];
}

- (void)paymentAuthorizationViewController:(PKPaymentAuthorizationViewController *)controller didAuthorizePayment:(PKPayment *)payment completion:(void (^)(PKPaymentAuthorizationStatus))completion{
    NSLog(@"Payment was authorized: %@", payment);
    
    PKPaymentToken *token = payment.token;
    NSData *paymentData = token.paymentData;
    NSString *applePayload = [paymentData hexadecimalString];
    [controller dismissViewControllerAnimated:TRUE completion:nil];
    
    CoreSaleAppleWallet *sale =[[CoreSaleAppleWallet alloc] init];
    sale.amount = [self getAmount];
    sale.payload = applePayload;
    
    [[WTPSTerminal singleton] processSale:sale];
    [[UiHelper singleton] showLoading:self.view isDeviceSale:NO];
    
    completion(PKPaymentAuthorizationStatusSuccess);
}

-(void)paymentAuthorizationViewControllerDidFinish:(PKPaymentAuthorizationViewController *)controller{
    NSLog(@"Finishing payment");
    [controller dismissViewControllerAnimated:TRUE completion:nil];
}

#pragma mark ------------- CoreAPIListener --------------

/*!
 * This method is triggered after error has occurred in the SDK.
 * @param error contains typedef enum of an error.
 */
-(void)onError:(CoreError) error withDescription:(NSString*) message{
    if(_tipAndTaxSwitch.hidden == NO){
        [self clearTipButtonHandle:nil];
        [self calculateAllAmounts];
    }
    NSString* errorValue = [[Util parseCoreError:error withMessage:message] stringByAppendingString:message];
    [[UiHelper singleton] showError:errorValue];
    [_statusLabel setText:errorValue];
    inTransaction = NO;
}

/*!
 * This method is triggered when there is an error coming from the device.
 * @param deviceError contains typedef enum of an error.
 */
-(void)onDeviceError:(CoreDeviceError) deviceError withDescription:(NSString*) message{
    NSString* errorValue = [Util parseCoreDeviceError:deviceError withDescription:message];
    [[UiHelper singleton] showError:errorValue];
    [_statusLabel setText:errorValue];
    inTransaction = NO;
}

/*!
 * Fires when signature is required for the transaction to be processed.
 * @param signature holds the signature.
 */
-(void)onSignatureRequired:(CoreSignature*)signature{
    _SignatureCanvas.signature = signature;
    [[UiHelper singleton] hideLoading];
    _mainView.hidden = YES;
    
    CATransition *animation = [CATransition animation];
    animation.duration = 1.0;
    animation.type = kCATransitionFade;
    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    [_signatureView.layer addAnimation:animation forKey:@"changeTextTransition"];
    
    _signatureView.hidden = NO;
    [UIView animateWithDuration:0.25 animations:^{_signatureView.alpha = 1.0;}];
}

/*!
 * Contains message coming from the SDK while processing the transaction.
 * @param message enum value of a message
 */
-(void)onMessage:(CoreMessage)message{
    NSString* messageValue = [Util parseCoreMessage:message];
    if(inTransaction && [[UiHelper singleton] isProgressShowing]){
        [[UiHelper singleton] updateMessage:messageValue];
    } else {
        [[UiHelper singleton] toastMessage:messageValue];
    }
    [_statusLabel setText:messageValue];
}

/*!
 * This method is called after refund has been processed in response to processRefund method.
 * @param refund contains CoreRefundResponse object retrieved from the server
 */
-(void)onRefundResponse:(CoreRefundResponse*)refundResponse{
    NSLog(@"onRefundResponse");
    self.amountView.text = @"";
    [_statusLabel setText:@"REFUND RESPONSE"];
    [[UiHelper singleton] hideLoading];
    if (cardDetails.presentingViewController != nil) {
        [cardDetails dismissViewControllerAnimated:YES completion:nil];
    }
    inTransaction = NO;
    UINavigationController *card= [storyboard instantiateViewControllerWithIdentifier:@"ReceiptViewControllerNavigation"];
    ReceiptViewController *receipt = [[card viewControllers] objectAtIndex:0];
    receipt.coreResponse = refundResponse;
    [self presentViewController:card animated:YES completion:nil];
}

- (void)onBalanceInquiryRetrieved:(CoreResponse*)response{
    NSLog(@"onBalanceInquiryRetrieved");
    self.amountView.text = @"";
    [_statusLabel setText:@"Balance Inquiry RESPONSE"];
}

/*!
 * Fires after transaction has been processed successfully in response to processSale method. Contains transaction response object from the server.
 * @param sale contains CoreSaleResponse object retrieved from the server
 */
-(void)onSaleResponse:(CoreSaleResponse*)sale{
    NSLog(@"onSaleResponse");
    self.amountView.text = @"";
    if(_tipAndTaxSwitch.hidden == NO){
        [self clearTipButtonHandle:nil];
        [self calculateAllAmounts];
    }
    [_statusLabel setText:@"SALE RESPONSE"];
    [[UiHelper singleton] hideLoading];
    if (cardDetails.presentingViewController != nil) {
        [cardDetails dismissViewControllerAnimated:YES completion:nil];
    }
    inTransaction = NO;
    UINavigationController *card= [storyboard instantiateViewControllerWithIdentifier:@"ReceiptViewControllerNavigation"];
    ReceiptViewController *receipt = [[card viewControllers] objectAtIndex:0];
    receipt.coreResponse = sale;
    [self presentViewController:card animated:YES completion:nil];
}

/*!
 * Sends back terminal settings object in response to init method.
 * @param settings holds the settings
 */
-(void)onSettingsRetrieved:(CoreSettings*)settings{
    [_statusLabel setText:@"Settings retrieved"];
    coreSettings = settings;
    
    UINavigationController *appSettingsNavigator = [storyboard instantiateViewControllerWithIdentifier:@"appSettingsViewControllerNavigation"];
    AppSettingsViewController *appSettingsController = [[appSettingsNavigator viewControllers] objectAtIndex:0];
    
    NSMutableDictionary* json = [[NSMutableDictionary alloc] init];
    json = [settings getAsJsonObject:settings];
    
    if([settings.features objectForKey:@"enableAutomaticSettle"] == nil || ![[settings.features valueForKey:@"enableAutomaticSettle"] boolValue]){
        [appSettingsController hideCloseBatchButton:NO];
        
    }else{
        [appSettingsController hideCloseBatchButton:YES];
    }
    
    if ([settings.features objectForKey:@"allowSurcharges"] != nil && [settings.features objectForKey:@"allowSurchargesForMobile"] != nil
        && [[settings.features valueForKey:@"allowSurcharges"] boolValue] && [[settings.features valueForKey:@"allowSurchargesForMobile"] boolValue]) {
        _bypassSurchargeLabel.hidden = NO;
        _bypassSurchargeSwitch.hidden = NO;
    }
    
    NSMutableArray* taxList = settings.taxListArray;
    if(taxList.count != 0){
        _tipAndTaxSwitch.hidden = NO;
        _tipAndTaxLabel.hidden = NO;
        taxMap = [NSMutableDictionary new];
        actionSheetTaxList = [[UIActionSheet alloc] initWithTitle:@"Tax"
                                                         delegate:self
                                                cancelButtonTitle:@"Cancel"
                                           destructiveButtonTitle:nil
                                                otherButtonTitles:nil];
        for (CoreTax *tax in taxList) {
            [taxMap setObject:tax forKey:[tax.percentage stringValue]];
            [actionSheetTaxList addButtonWithTitle:[tax.percentage stringValue]];
        }
        actionSheetTaxList.tag = 120;
    }
    
    NSMutableArray* tipList = settings.tipListArray;
    if(tipList.count != 0){
        _tipAndTaxSwitch.hidden = NO;
        _tipAndTaxLabel.hidden = NO;
        tipMap = [NSMutableDictionary new];
        actionSheetTipList = [[UIActionSheet alloc] initWithTitle:@"Tip"
                                                         delegate:self
                                                cancelButtonTitle:@"Cancel"
                                           destructiveButtonTitle:nil
                                                otherButtonTitles:nil];
        for (CoreTip *tip in tipList) {
            if([tip.tipType isEqualToString:@"PERCENTAGE"]){
                [tipMap setObject:tip forKey:[tip.percentage stringValue]];
                [actionSheetTipList addButtonWithTitle:[tip.percentage stringValue]];
            }
        }
        actionSheetTipList.tag = 130;
    }
}

/*!
 * Fires when device gets connected.
 * @param type represents connected device
 */
-(void)onDeviceConnected:(DeviceEnum)type withDeviceInfo:(NSDictionary*) deviceInfo{
    nfcEnabledSupported = [deviceInfo valueForKey:@"isSupportedNfc"];
    [[UiHelper singleton] hideLoading];
    [[UiHelper singleton] toastMessage:@"Device connected"];
    [_statusLabel setText:@"Device connected"];
    [_connectIcon setImage:[UIImage imageNamed:@"connected.png"] forState:UIControlStateNormal];
    //[[WTPSTerminal singleton] enableDelayedAuth:[NSNumber numberWithInt:10]];
}

/*!
 * Fires when device gets disconnected.
 * @param type represents disconnected device
 */
-(void)onDeviceDisconnected:(DeviceEnum)type{
    [[UiHelper singleton] hideLoading];
    [[UiHelper singleton] toastMessage:@"Device disconnected"];
    [_statusLabel setText:@"Device disconnected"];
    [_connectIcon setImage:[UIImage imageNamed:@"disconnected.png"] forState:UIControlStateNormal];
    inTransaction = NO;
}

/*!
 * This method is called when the application selection is required.
 * @param applications represents the array of applications to choose from
 */
-(void)onSelectApplication:(NSArray*)applications{
    [[UiHelper singleton] hideLoading];
    
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"Applications"
                                                             delegate:self
                                                    cancelButtonTitle:nil
                                               destructiveButtonTitle:nil
                                                    otherButtonTitles:nil];
    for (int i = 0; i< [applications count]; i++) {
        [actionSheet addButtonWithTitle:[applications objectAtIndex:i]];
    }
    actionSheet.tag = 80;
    [actionSheet showInView:self.view];
}

/*!
 * This method is called when the bluetooth device selection is required.
 * @param type represents the array of devices to choose from
 */
-(void)onSelectBTDevice:(NSArray*)devices{
    [[UiHelper singleton] hideLoading];

    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC));
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        if(bluetoothSelection != nil){
            [bluetoothSelection  dismissWithClickedButtonIndex:0 animated:NO];
        }
        [self.view endEditing:YES];
        bluetoothSelection = [[UIActionSheet alloc] initWithTitle:@"Bluetooth devices"
                                                         delegate:self
                                                cancelButtonTitle:@"Cancel"
                                           destructiveButtonTitle:nil
                                                otherButtonTitles:nil];
        
        for (id object in devices) {
            if([object isKindOfClass:[NSString class]]){
                [bluetoothSelection addButtonWithTitle:object];
            }else{
                if ([object isKindOfClass:[EAAccessory class]]){
                    EAAccessory* deviceName = (EAAccessory*) object;
                    [bluetoothSelection addButtonWithTitle:deviceName.serialNumber];
                } else  if ([object isKindOfClass:[CBPeripheral class]]){
                    CBPeripheral* deviceName = (CBPeripheral*) object;
                    [bluetoothSelection addButtonWithTitle:deviceName.name];
                }
            }
        }
        bluetoothSelection.tag = 90;
        [bluetoothSelection showInView:self.view];
    });
}

/*!
 * This method is called when there is a problem connecting to a device.
 */
-(void) onDeviceConnectionError{
    NSLog(@"onDeviceConnectionError");
    [[UiHelper singleton] showError:@"Device connection error"];
    [_statusLabel setText:@"Device connection error"];
    inTransaction = NO;
}

/*!
 * This method is called after reversal has been processed.
 * @param sale contains reversal object retrieved from the server
 */
-(void) onReversalRetrieved:(CoreResponse*)reversalResponse{
    NSLog(@"onReversalRetrieved");
    [[UiHelper singleton] hideLoading];
    inTransaction = NO;
    NSString *resp = [NSString stringWithFormat:@"Approval Code: %@ \n Amount: %@ \n Description: %@ \n Currency: %@ \n UniqueRef: %@ \n DateTime: %@ \n",reversalResponse.approvalCode,reversalResponse.authorizedAmount,reversalResponse.descriptionCode,getCurrencyData(reversalResponse.currency)[2],reversalResponse.uniqueRef, reversalResponse.dateTime];
    [[UiHelper singleton] showSuccess:@"Reversal Response" withMessage:resp];
}

/*!
 * Information about the device.
 * @param deviceInfo returned
 */
- (void) onDeviceInfoReturned:(NSDictionary*)deviceInfo{
    NSLog(@"onDeviceInfoReturned");
    [_statusLabel setText:@"Device info returned"];
    NSMutableString* deviceInfoData = [[NSMutableString alloc] init];
    inTransaction = NO;
    NSString* sdkVersion = [[WTPSTerminal singleton] getSdkVersion];
    [deviceInfoData appendString:[NSString stringWithFormat:@"SDK Version: %@ \n\n" , sdkVersion]];
    for (NSString* key in deviceInfo) {
        NSString* value = [deviceInfo objectForKey:key];
        [deviceInfoData appendString:[NSString stringWithFormat:@"%@: %@ \n" , key,value]];
    }
    [[UiHelper singleton] showSuccess:@"Device Info" withMessage:deviceInfoData];
}

/**
 * Fires when delayed auth is enabled and the amount need to be set here before calling confirmAmount.
 *
 * @param coreSale contains coreSale object
 */
- (void) onRequestSetAmount:(CoreSale*)coreSale{ 
    [[UiHelper singleton] showRequestAmountEdit:coreSale withViewController:self];
}

/**
 * This method is called after updating transaction in response to updateTransaction method.
 *
 * @param response contains response object
 */
- (void)onRequestUpdateResponse:(CoreResponse *)response{
    if([response.code isEqualToString:@"A"]){
        [[UiHelper singleton] toastMessage:@"Transaction update successful"];
    } else {
        [[UiHelper singleton] toastMessage:response.descriptionCode];
    }
}

/**
 * Fires after offline transaction has been processed in response to ProcessSale method. Contains a coreSale request.
 *
 * @param saleRequest contains sale object
 */
- (void)onOfflineSaleRequest:(CoreSale *)saleRequest{
    NSLog(@"onOfflineSaleRequest");
    [[UiHelper singleton] showError:@"Offline transaction"];
    [_statusLabel setText:@"Offline transaction"];
    
    if([RestConnector isPayconexSDK]){
        // ----- Sample code to send the transaction online using Rest-connector directly once the internet comes back online
        NSDictionary* dict = [saleRequest convertToDictionary];
        CoreTerminal* coreTerminal = [CoreTerminal new];
        coreTerminal.url = @"https://cert.payconex.net/api";
        coreTerminal.terminalId = @"220614969941";
        coreTerminal.secret = @"0e8d38a08f2d4919a5a27ec83a6e8d76";
        coreTerminal.currency = USD;
        coreTerminal.terminalType = @"CHP";
        
        dispatch_async( dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            NSError* error = nil;
            BOOL isOffline = YES;
            int attempt = 0;
            while (isOffline && attempt < 5) {
                isOffline = [[WTPSTerminal singleton] offlineSdkMode];
                if(isOffline == NO){
                    CoreSaleResponse *response = [RestConnector sendSaleAsDictionary:dict withTerminal:coreTerminal error:&error];
                    if(error == nil){ // check for errors
                        NSLog(@"Successful offline sale response");
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [[UiHelper singleton] toastMessage:@"Successful offline sale response."];
                        });
                    }
                }
                [NSThread sleepForTimeInterval:10.000];
                attempt++;
            }
        });
    }
}

-(void) onTransactionReportRetrieved:(CoreTransactionReports*)respose{
    
}

@end
