#import "SecureCardViewController.h"

@interface SecureCardViewController()<UITabBarControllerDelegate>
@property (weak, nonatomic) IBOutlet UILabel *statusLabel;
@property (weak, nonatomic) IBOutlet UITextField *merchantReferenceTextField;
@property (weak, nonatomic) IBOutlet UITextField *secureCardReferenceTextField;
@property (weak, nonatomic) IBOutlet UIButton *registerButton;
@property (weak, nonatomic) IBOutlet UIButton *updateButton;
@property (weak, nonatomic) IBOutlet UIButton *deleteButton;
@property (weak, nonatomic) IBOutlet UIView *topView;
@property (weak, nonatomic) IBOutlet UIButton *saleButton;
@property (weak, nonatomic) IBOutlet UITextField *amountTextField;

@end


@implementation SecureCardViewController
{
    UIColor* color;
    UIStoryboard* storyboard;
    BOOL doUpdate;
    CardDetailsViewController* cardDetails;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.tabBarController.delegate = self;
    storyboard = [UIStoryboard storyboardWithName:@"Mainview" bundle:nil];
    color = UIColorFromRGB(0xC11D03);
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Settings" style:UIBarButtonItemStylePlain target:self action:@selector(openSettings)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
    [self setTheme];
    [self setMode];
    doUpdate = NO;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]
                                   initWithTarget:self
                                   action:@selector(dismissKeyboard)];
    
    [self.view addGestureRecognizer:tap];
}

- (void)viewWillAppear:(BOOL)animated{
    [[WTPSTerminal singleton] registerCoreAPIDeviceListener:self];
    [[WTPSTerminal singleton] registerCoreAPISaleListener:self];
    [[WTPSTerminal singleton] registerCoreAPISecureCardListener:self];
    [[WTPSTerminal singleton] registerCoreAPIMessageListener:self];
}

- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController{
    if(![viewController.restorationIdentifier isEqualToString:@"secureCardViewControllerNavigation"]){
        [[WTPSTerminal singleton] unRegisterCoreAPIDeviceListener:self];
        [[WTPSTerminal singleton] unRegisterCoreAPISaleListener:self];
        [[WTPSTerminal singleton] unRegisterCoreAPISecureCardListener:self];
        [[WTPSTerminal singleton] unRegisterCoreAPIMessageListener:self];
    }
}

-(void)dismissKeyboard {
    [_amountTextField resignFirstResponder];
    [_merchantReferenceTextField resignFirstResponder];
    [_secureCardReferenceTextField resignFirstResponder];
}

- (void) setTheme{
    self.navigationController.navigationBar.barTintColor = color;
    self.tabBarController.tabBar.tintColor = color;
}

- (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];
    }
}

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

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

- (IBAction)saleButtonHandle:(id)sender {
    if(self.merchantReferenceTextField.text.length <= 0){
        [[UiHelper singleton] animateWrongInput:self.merchantReferenceTextField];
        return;
    }
    if(self.amountTextField.text.length <= 0){
        [[UiHelper singleton] animateWrongInput:self.merchantReferenceTextField];
        return;
    }
    doUpdate = NO;
    UINavigationController *card= [storyboard instantiateViewControllerWithIdentifier:@"cardDetailsNavigation"];
    cardDetails = [[card viewControllers] objectAtIndex:0];
    cardDetails.cardDetaildViewType = CARD_DETAILS_SECURE_CARD;
    cardDetails.secureCardType = SECURE_CARD_TYPE_SALE;
    cardDetails.merchantReference = _merchantReferenceTextField.text;
    cardDetails.secureCardReference = _secureCardReferenceTextField.text;
    cardDetails.amount = [NSNumber numberWithDouble:[[_amountTextField text] doubleValue]];
    [self presentViewController:card animated:YES completion:nil];
}

- (IBAction)registerHandle:(id)sender {
    if(self.merchantReferenceTextField.text.length <= 0){
        [[UiHelper singleton] animateWrongInput:self.merchantReferenceTextField];
        return;
    }
    doUpdate = NO;
    UINavigationController *card= [storyboard instantiateViewControllerWithIdentifier:@"cardDetailsNavigation"];
    cardDetails = [[card viewControllers] objectAtIndex:0];
    cardDetails.cardDetaildViewType = CARD_DETAILS_SECURE_CARD;
    cardDetails.secureCardType = SECURE_CARD_TYPE_REGISTER;
    cardDetails.merchantReference = _merchantReferenceTextField.text;
    cardDetails.secureCardReference = _secureCardReferenceTextField.text;
    [self presentViewController:card animated:YES completion:nil];
}

- (IBAction)updateHandle:(id)sender {
    if(self.merchantReferenceTextField.text.length <= 0){
        [[UiHelper singleton] animateWrongInput:self.merchantReferenceTextField];
        return;
    }
    doUpdate = YES;
    [[WTPSTerminal singleton] retrieveSecureCard:_merchantReferenceTextField.text];
}

- (IBAction)deleteHandle:(id)sender {
    if(self.merchantReferenceTextField.text.length <= 0){
        [[UiHelper singleton] animateWrongInput:self.merchantReferenceTextField];
        return;
    }
    doUpdate = NO;

    CoreSecureCard* secureCard = [[CoreSecureCard alloc] init];
    
    secureCard.merchantReference = _merchantReferenceTextField.text;
    secureCard.cardReference = _secureCardReferenceTextField.text;
    
    [[WTPSTerminal singleton] deleteSecureCard:secureCard];
    [[UiHelper singleton] showLoading:self.view isDeviceSale:NO];
}

#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{
    NSString* errorValue = [Util parseCoreError:error withMessage:message];
    [[UiHelper singleton] showError:errorValue];
    [_statusLabel setText:errorValue];
}

/*!
 * 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];
}

/*!
 * Fires when signature is required for the transaction to be processed.
 * @param signature holds the signature.
 */
-(void)onSignatureRequired:(CoreSignature*)signature{
    
}

/*!
 * 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 (cardDetails.presentingViewController != nil && [[UiHelper singleton] isProgressShowing]) {
        [[UiHelper singleton] updateMessage:messageValue];
    }else {
        [[UiHelper singleton] toastMessage:messageValue];
    }
    [_statusLabel setText:messageValue];
}

/*!
 * 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");
    [[UiHelper singleton] hideLoading];
    if (cardDetails.presentingViewController != nil) {
        [cardDetails dismissViewControllerAnimated:YES completion:nil];
    }
    NSMutableString *resp = [[NSString stringWithFormat:@"CardHolderName: %@ \n Card Type: %@ \n Card Number: %@ \n Expiry Date: %@ \n Approval Code: %@ \n Amount: %@ \n Description: %@ \n Currency: %@ \n UniqueRef: %@ \n DateTime: %@ \n",sale.cardHolderName,sale.cardType,sale.cardNumber,sale.expiryDate,sale.approvalCode,sale.authorizedAmount,sale.descriptionCode,getCurrencyData(sale.currency)[2],sale.uniqueRef, sale.dateTime] mutableCopy];
    if(sale.secureCardReference != nil){
        [resp appendString:@"Secure Card Reference: "];
        [resp appendString:sale.secureCardReference];
        _secureCardReferenceTextField.text = sale.secureCardReference;
    }
    [[UiHelper singleton] showSuccess:@"Sale Response" withMessage:resp];
}

/*!
 * Fires after the secure card has been registered/edited/deleted successfully.
 * @param secureCardResponse contains CoreSecureCardResponse object retrieved from the server
 */
-(void)onSecureCardResponse:(CoreSecureCardResponse*)secureCardResponse{
    NSLog(@"onSecureCardResponse");
    [_statusLabel setText:@"onSecureCardResponse"];
    [[UiHelper singleton] hideLoading];
    
    if(doUpdate){
        doUpdate = NO;
        CoreSecureCard * secureCard = secureCardResponse.coreSecureCard;
        UINavigationController *card= [storyboard instantiateViewControllerWithIdentifier:@"cardDetailsNavigation"];
        cardDetails = [[card viewControllers] objectAtIndex:0];
        cardDetails.secureCard = secureCard;
        cardDetails.cardDetaildViewType = CARD_DETAILS_SECURE_CARD;
        cardDetails.secureCardType = SECURE_CARD_TYPE_UPDATE;
        cardDetails.merchantReference = _merchantReferenceTextField.text;
        cardDetails.secureCardReference = _secureCardReferenceTextField.text;
        [self presentViewController:card animated:YES completion:nil];
    } else {
        _secureCardReferenceTextField.text = secureCardResponse.secureCardReference;
        if (cardDetails.presentingViewController != nil) {
            [cardDetails dismissViewControllerAnimated:YES completion:nil];
        }
        NSString *resp = [NSString stringWithFormat:@"Secure Card Reference Number: %@ \n Secure Card Description: %@ \n",secureCardResponse.secureCardReference,secureCardResponse.secureCardDescription];
        [[UiHelper singleton] showSuccess:@"SecureCard Response" withMessage:resp];
    }
}

/*!
 * Fires when device gets connected.
 * @param type represents connected device
 */
-(void)onDeviceConnected:(DeviceEnum)type withDeviceInfo:(NSDictionary*) deviceInfo{
    
}

/*!
 * Fires when device gets disconnected.
 * @param type represents disconnected device
 */
-(void)onDeviceDisconnected:(DeviceEnum)type{
    
}

/*!
 * This method is called when the application selection is required.
 * @param applications represents the array of applications to choose from
 */
-(void)onSelectApplication:(NSArray*)applications{
    
}

/*!
 * 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{
    
}

/*!
 * This method is called when there is a problem connecting to a device.
 */
-(void) onDeviceConnectionError{
    
}

/*!
 * Information about the device.
 * @param deviceInfo returned
 */
- (void) onDeviceInfoReturned:(NSDictionary*)deviceInfo{
    
}

/**
 * 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{
    
}

/**
 * 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{
    
}
@end
