#import "CardDetailsViewController.h"

@interface CardDetailsViewController()

@property (weak, nonatomic) IBOutlet UIButton *submitButton;
@property (weak, nonatomic) IBOutlet UITextField *cardNumberTextField;
@property (weak, nonatomic) IBOutlet UITextField *nameTextField;
@property (weak, nonatomic) IBOutlet UITextField *cvvTextField;
@property (weak, nonatomic) IBOutlet UITextField *reasonTextField;
@property (weak, nonatomic) IBOutlet UIButton *cardTypeButton;
@property (weak, nonatomic) IBOutlet UIButton *monthButton;
@property (weak, nonatomic) IBOutlet UIButton *yearButton;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UIView *cardDetailsView;
@property (weak, nonatomic) IBOutlet UIView *secureCardDetailsView;
@property (weak, nonatomic) IBOutlet UITextField *permittedTerminalTexField;
@property (weak, nonatomic) IBOutlet UITextField *emailTexField;
@property (weak, nonatomic) IBOutlet UITextField *phoneTexField;
@property (weak, nonatomic) IBOutlet UITextField *customFieldNameOneTexField;
@property (weak, nonatomic) IBOutlet UITextField *customFieldValueOneTexField;
@property (weak, nonatomic) IBOutlet UITextField *customFieldNameTwoTexField;
@property (weak, nonatomic) IBOutlet UITextField *customFieldValueTwoTexField;
@property (weak, nonatomic) IBOutlet UITextField *customFieldNameThreeTexField;
@property (weak, nonatomic) IBOutlet UITextField *customFieldValueThreeTexField;
@property (weak, nonatomic) IBOutlet UITextField *customFieldNameFourTexField;
@property (weak, nonatomic) IBOutlet UITextField *customFieldValueFourTexField;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *secureCardDetailsViewHeightConstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *cardDetialsViewHeightConstraint;

@end


@implementation CardDetailsViewController
{
    UIStoryboard* storyboard;
    UIColor* color;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];
    color = UIColorFromRGB(0xC11D03);
    [self setTheme];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]
                                   initWithTarget:self
                                   action:@selector(dismissKeyboard)];
    
    [self.view addGestureRecognizer:tap];
    storyboard = [UIStoryboard storyboardWithName:@"Mainview" bundle:nil];
    [_cardTypeButton setTitle:@"VISA" forState:UIControlStateNormal];
    
    if(_cardDetaildViewType == CARD_DETAILS_SALE){
        _reasonTextField.hidden = YES;
        _secureCardDetailsView.hidden = YES;
        _secureCardDetailsViewHeightConstraint.constant = 0;
    } else if(_cardDetaildViewType == CARD_DETAILS_REFUND){
        _reasonTextField.hidden = NO;
        _secureCardDetailsView.hidden = YES;
        _secureCardDetailsViewHeightConstraint.constant = 0;
    } else {
        _reasonTextField.hidden = YES;
        _secureCardDetailsView.hidden = NO;
        if([[WTPSTerminal singleton] getDevice] != NODEVICE){
            _cardDetailsView.hidden = YES;
            _cardDetialsViewHeightConstraint.constant = 0;
        }
    }
    
    if(_secureCard != nil){
        if(_secureCard.tokenMethod.keyedSecureCard != nil){
            self.cvvTextField.text = _secureCard.tokenMethod.keyedSecureCard.cvv;
            self.nameTextField.text = _secureCard.tokenMethod.keyedSecureCard.cardHolderName;
            self.cardNumberTextField.text = _secureCard.tokenMethod.keyedSecureCard.cardNumber;
            NSString* month = [_secureCard.tokenMethod.keyedSecureCard.expiryDate substringToIndex:2];
            NSString* year = [_secureCard.tokenMethod.keyedSecureCard.expiryDate substringFromIndex:2];
            
            [_monthButton setTitle:month forState:UIControlStateNormal];
            [_yearButton setTitle:year forState:UIControlStateNormal];
        }
        
        if(_secureCard.customFields != nil){
            CoreCustomField *custom1 = [_secureCard.customFields objectAtIndex:0];
            self.customFieldNameOneTexField.text = custom1.name;
            self.customFieldValueOneTexField.text = custom1.value;
            
            if([_secureCard.customFields count] > 1){
                CoreCustomField *custom2 = [_secureCard.customFields objectAtIndex:1];
                self.customFieldNameTwoTexField.text = custom2.name;
                self.customFieldValueTwoTexField.text = custom2.value;
            }
            
            if([_secureCard.customFields count] > 2){
                CoreCustomField *custom3 = [_secureCard.customFields objectAtIndex:2];
                self.customFieldNameThreeTexField.text = custom3.name;
                self.customFieldValueThreeTexField.text = custom3.value;
            }
            
            if([_secureCard.customFields count] > 3){
                CoreCustomField *custom4 = [_secureCard.customFields objectAtIndex:3];
                self.customFieldNameFourTexField.text = custom4.name;
                self.customFieldValueFourTexField.text = custom4.value;
            }
        }
        
        self.permittedTerminalTexField.text = _secureCard.permittedTerminals;
        self.emailTexField.text = _secureCard.email;
        self.phoneTexField.text = _secureCard.mobileNumber;
    }
}

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

- (void) back{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (IBAction)cardTypeButtonHandle:(id)sender {
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@""
                                                             delegate:self
                                                    cancelButtonTitle:@"Cancel"
                                               destructiveButtonTitle:nil
                                                    otherButtonTitles:@"VISA", @"MASTERCARD",@"AMEX",@"DISCOVER",@"MAESTRO",@"JCB",@"DINERS",@"ELECTRON", nil];
    actionSheet.tag = 1;
    [actionSheet showInView:self.view];
}

-(void)dismissKeyboard {
    [_cardNumberTextField resignFirstResponder];
    [_nameTextField resignFirstResponder];
    [_cvvTextField resignFirstResponder];
    [_reasonTextField resignFirstResponder];
    [_permittedTerminalTexField resignFirstResponder];
    [_emailTexField resignFirstResponder];
    [_phoneTexField resignFirstResponder];
    [_customFieldNameOneTexField resignFirstResponder];
    [_customFieldValueOneTexField resignFirstResponder];
    [_customFieldNameTwoTexField resignFirstResponder];
    [_customFieldValueTwoTexField resignFirstResponder];
    [_customFieldNameThreeTexField resignFirstResponder];
    [_customFieldValueThreeTexField resignFirstResponder];
    [_customFieldNameFourTexField resignFirstResponder];
    [_customFieldValueFourTexField resignFirstResponder];
}

- (IBAction)submitButtonHandle:(id)sender {
    if([[WTPSTerminal singleton] getDevice] == NODEVICE){
        if([_cardNumberTextField.text isEqualToString:@""]){
            [[UiHelper singleton] showWarning:@"Invalid card number"];
            return;
        }
        if( [_nameTextField.text isEqualToString:@""] ){
            [[UiHelper singleton] showWarning:@"Invalid name"];
            return;
        }
        if([_cvvTextField.text isEqualToString:@""]){
            [[UiHelper singleton] showWarning:@"Invalid cvv"];
            return;
        }
        if([_cardTypeButton.currentTitle isEqualToString:@"CARD TYPE"]){
            [[UiHelper singleton] showWarning:@"Invalid card type"];
            return;
        }
        if([_monthButton.currentTitle isEqualToString:@"Month"]){
            [[UiHelper singleton] showWarning:@"Invalid month"];
            return;
        }
        if([_yearButton.currentTitle isEqualToString:@"Year"]){
            [[UiHelper singleton] showWarning:@"Invalid year"];
            return;
        }
    }
    if(_cardDetaildViewType == CARD_DETAILS_SALE){
        [self doKeyedSale];
    } else if(_cardDetaildViewType == CARD_DETAILS_REFUND){
        [self doRefund];
    } else {
        [self doSecureCard];
    }
}

- (void) doKeyedSale{
    CoreSaleKeyed* saleKeyed = [[CoreSaleKeyed alloc] init];
    saleKeyed.amount = [NSNumber numberWithDouble: [self.amount doubleValue]];
    saleKeyed.cardCvv = self.cvvTextField.text;
    saleKeyed.cardHolderName = self.nameTextField.text;
    saleKeyed.cardNumber = self.cardNumberTextField.text;
    saleKeyed.cardType= self.cardTypeButton.currentTitle;
    NSString* year = [self.yearButton.currentTitle substringFromIndex:2];
    saleKeyed.expiryDate = [self.monthButton.currentTitle stringByAppendingString:year];
    [[WTPSTerminal singleton] processSale:saleKeyed];
    [[UiHelper singleton] showLoading:self.view isDeviceSale:NO];
}

- (void) doRefund{
    if([_reasonTextField.text isEqualToString:@""]){
        [[UiHelper singleton] showWarning:@"Invalid reason"];
        return;
    }
    CoreUnreferencedRefund *refund =[[CoreUnreferencedRefund alloc] init];
    refund.amount = [NSNumber numberWithDouble: [self.amount doubleValue]];
    refund.reason=self.reasonTextField.text;
    refund.cardCvv = self.cvvTextField.text;
    refund.cardHolderName = self.nameTextField.text;
    refund.cardNumber = self.cardNumberTextField.text;
    refund.cardType= self.cardTypeButton.currentTitle;
    NSString* year = [self.yearButton.currentTitle substringFromIndex:2];
    refund.expiryDate = [self.monthButton.currentTitle stringByAppendingString:year];
    [[WTPSTerminal singleton] processUnreferencedRefund:refund];
    [[UiHelper singleton] showLoading:self.view isDeviceSale:NO];
}

- (void) doSecureCard{
    CoreSecureCard* secureCard = [[CoreSecureCard alloc] init];
    
    if([[WTPSTerminal singleton] getDevice] == NODEVICE){
        if(_secureCardType == SECURE_CARD_TYPE_UPDATE){
            if(_secureCard.tokenMethod.keyedSecureCard == nil){
                secureCard.tokenMethod.keyedSecureCard = [[CoreKeyedSecureCard alloc] init];
            }
            if(![_cardNumberTextField.text containsString:@"*"]){
                secureCard.cardEntryMode = KEYED;
            }
            secureCard.tokenMethod = _secureCard.tokenMethod;
        }else{
            secureCard.tokenMethod = [[CoreTokenMethod alloc] init];
            secureCard.tokenMethod.keyedSecureCard = [[CoreKeyedSecureCard alloc] init];
            secureCard.cardEntryMode = KEYED;
        }
        secureCard.tokenMethod.keyedSecureCard.cvv = _cvvTextField.text;
        secureCard.tokenMethod.keyedSecureCard.cardHolderName = _nameTextField.text;
        secureCard.tokenMethod.keyedSecureCard.cardNumber = _cardNumberTextField.text;
        NSString* year = [self.yearButton.currentTitle substringFromIndex:2];
        secureCard.tokenMethod.keyedSecureCard.expiryDate = [self.monthButton.currentTitle stringByAppendingString:year];
    }
    
    CoreCustomField *field;
    NSMutableArray *customFields = nil;
    
    if(self.customFieldNameOneTexField.text.length > 0){
        if(self.customFieldValueOneTexField.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.customFieldNameOneTexField.text;
        field.value = self.customFieldValueOneTexField.text;
        [customFields addObject:field];
    }
    
    if(self.customFieldNameTwoTexField.text.length > 0){
        if(self.customFieldValueTwoTexField.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.customFieldNameTwoTexField.text;
        field.value = self.customFieldValueTwoTexField.text;
        [customFields addObject:field];
    }
    
    if(self.customFieldNameThreeTexField.text.length > 0){
        if(self.customFieldValueThreeTexField.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.customFieldNameThreeTexField.text;
        field.value = self.customFieldValueThreeTexField.text;
        [customFields addObject:field];
    }
    
    if(self.customFieldNameFourTexField.text.length > 0){
        if(self.customFieldValueFourTexField.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.customFieldNameFourTexField.text;
        field.value = self.customFieldValueFourTexField.text;
        [customFields addObject:field];
    }
    
    if(_secureCardType == SECURE_CARD_TYPE_SALE){
        CoreSale*  sale = [[CoreSale alloc] init];
        sale.amount = _amount;
        if([[WTPSTerminal singleton] getDevice] != NODEVICE){
            sale.coreSecureCard = secureCard;
            sale.coreSecureCard.merchantReference = _merchantReference;
            sale.coreSecureCard.permittedTerminals = self.permittedTerminalTexField.text;
            sale.coreSecureCard.customFields = customFields;
            sale.coreSecureCard.email = self.emailTexField.text;
            sale.coreSecureCard.mobileNumber = self.phoneTexField.text;
            sale.signatureCollection = MANUAL;
            [[WTPSTerminal singleton] processSale:sale];
        }else{
            CoreSaleKeyed* saleKeyed = [[CoreSaleKeyed alloc] init];
            saleKeyed.amount = _amount;
            saleKeyed.cardCvv = self.cvvTextField.text;
            saleKeyed.cardHolderName = self.nameTextField.text;
            saleKeyed.cardNumber = self.cardNumberTextField.text;
            saleKeyed.cardType= self.cardTypeButton.currentTitle;
            NSString* year = [self.yearButton.currentTitle substringFromIndex:2];
            saleKeyed.expiryDate = [self.monthButton.currentTitle stringByAppendingString:year];
            saleKeyed.coreSecureCard = secureCard;
            saleKeyed.coreSecureCard.permittedTerminals = self.permittedTerminalTexField.text;
            saleKeyed.coreSecureCard.customFields = customFields;
            saleKeyed.coreSecureCard.email = self.emailTexField.text;
            saleKeyed.coreSecureCard.mobileNumber = self.phoneTexField.text;
            saleKeyed.coreSecureCard.merchantReference = _merchantReference;
            [[WTPSTerminal singleton] processSale:saleKeyed];
        }
    }else{
        secureCard.permittedTerminals = self.permittedTerminalTexField.text;
        secureCard.customFields = customFields;
        secureCard.email = self.emailTexField.text;
        secureCard.mobileNumber = self.phoneTexField.text;
        secureCard.merchantReference = _merchantReference;
        
        if(_secureCardType == SECURE_CARD_TYPE_REGISTER){
            [[WTPSTerminal singleton] registerSecureCard:secureCard];
            
        }else{
            [[WTPSTerminal singleton] editSecureCard:secureCard];
        }
    }
    [[UiHelper singleton] showLoading:self.view isDeviceSale:NO];
}

- (IBAction)monthButtonHandle:(id)sender {
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@""
                                                             delegate:self
                                                    cancelButtonTitle:@"Cancel"
                                               destructiveButtonTitle:nil
                                                    otherButtonTitles:@"01",@"02",@"03",@"04",@"05",@"06",@"07",@"08",@"09",@"10",@"11",@"12", nil];
    actionSheet.tag = 2;
    [actionSheet showInView:self.view];
}

- (IBAction)yearButtonHandle:(id)sender {
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@""
                                                             delegate:self
                                                    cancelButtonTitle:@"Cancel"
                                               destructiveButtonTitle:nil
                                                    otherButtonTitles:@"2017", @"2018",@"2019",@"2020",@"2021",@"2022",@"2023",@"2024",@"2025",@"2026",@"2027",@"2028",@"2029",@"2030", nil];
    actionSheet.tag = 3;
    [actionSheet showInView:self.view];
}

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

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (actionSheet.tag == 1) {
        [_cardTypeButton setTitle:[actionSheet buttonTitleAtIndex:buttonIndex] forState:UIControlStateNormal];
    } else if (actionSheet.tag == 2) {
        [_monthButton setTitle:[actionSheet buttonTitleAtIndex:buttonIndex] forState:UIControlStateNormal];
    } else if (actionSheet.tag == 3) {
        [_yearButton setTitle:[actionSheet buttonTitleAtIndex:buttonIndex] forState:UIControlStateNormal];
    }
}

@end
