#import "TransactionDetailViewController.h"

@interface TransactionDetailViewController()

@property (weak, nonatomic) IBOutlet UIView *topView;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UILabel *status;
@property (weak, nonatomic) IBOutlet UIButton *refundButton;
@property (weak, nonatomic) IBOutlet UIButton *voidButton;
@property (weak, nonatomic) IBOutlet UIView *refundView;
@property (weak, nonatomic) IBOutlet UIButton *cancelButton;
@property (weak, nonatomic) IBOutlet UIButton *submitButton;
@property (weak, nonatomic) IBOutlet UITextField *amountField;
@property (weak, nonatomic) IBOutlet UITextField *reasonField;
@property (weak, nonatomic) IBOutlet UIButton *tipButton;
@property (weak, nonatomic) IBOutlet UIView *tipAdjustmentView;
@property (weak, nonatomic) IBOutlet UIButton *tipCancelButton;
@property (weak, nonatomic) IBOutlet UIButton *tipSubmitButton;
@property (weak, nonatomic) IBOutlet UISegmentedControl *tipTypeSegment;
@property (weak, nonatomic) IBOutlet UITextField *tipValue;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *voidHeightConst;
@property (weak, nonatomic) IBOutlet UIButton *reversalButton;

@end


@implementation TransactionDetailViewController
{
    UIColor* color;
    NSMutableArray *tableData;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    color = UIColorFromRGB(0xC11D03);
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];
    _refundView.hidden = YES;
    _tipAdjustmentView.hidden = YES;
    [self.amountField setDelegate:self];
    _refundButton.hidden = YES;
    _voidButton.hidden = YES;
    _tipButton.hidden = YES;
    _reversalButton.hidden = YES;
    [self setTheme];
    tableData = [[NSMutableArray alloc] init];
    [tableData addObject:[NSString stringWithFormat:@"CardHolderName ;%@" ,  _summary.cardHolderName]];
    [tableData addObject:[NSString stringWithFormat:@"Card Type ;%@" ,  _summary.cardType]];
    [tableData addObject:[NSString stringWithFormat:@"Card Number ;%@" ,  _summary.cardNumber]];
    [tableData addObject:[NSString stringWithFormat:@"Amount ;%@" ,  [[_summary.amount stringValue] stringByAppendingString:getCurrencyData(_summary.currency)[2]]]];
    [tableData addObject:[NSString stringWithFormat:@"Order ID ;%@" ,  _summary.orderId]];
    [tableData addObject:[NSString stringWithFormat:@"Currency ;%@" ,  getCurrencyData(_summary.currency)[2]]];
    [tableData addObject:[NSString stringWithFormat:@"UniqueRef ;%@" ,  _summary.uniqueRef]];
    if (_summary.surcharge != nil) {
        [tableData addObject:[NSString stringWithFormat:@"Surcharge Amount ;%@" ,  [[_summary.surcharge.amount stringValue] stringByAppendingString:getCurrencyData(_summary.surcharge.currency)[2]]]];
        [tableData addObject:[NSString stringWithFormat:@"Surcharge Percent ;%@" ,  _summary.surcharge.percentage]];
    }
    [tableData addObject:[NSString stringWithFormat:@"Transaction Date ;%@" ,  _summary.transactionDate]];
    if(_summary.transactionState != nil){
        [tableData addObject:[NSString stringWithFormat:@"Transaction State ;%@" ,  _summary.transactionState]];
    }
    [tableData addObject:[NSString stringWithFormat:@"Transaction Status ;%@" ,  _summary.transactionStatus]];
    [tableData addObject:[NSString stringWithFormat:@"Transaction Type ;%@" ,  _summary.transactionType]];
    [tableData addObject:[NSString stringWithFormat:@"Expiry Date ;%@" ,  _summary.expiryDate]];
    [tableData addObject:[NSString stringWithFormat:@"Code ;%@" ,  _summary.code]];
    [tableData addObject:[NSString stringWithFormat:@"Approval Code ;%@" ,  _summary.approvalCode]];
    [tableData addObject:[NSString stringWithFormat:@"Description ;%@" ,  _summary.descriptionCode]];

    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]
                                   initWithTarget:self
                                   action:@selector(dismissKeyboard)];
    
    [self.view addGestureRecognizer:tap];
    
    if([_summary.transactionType isEqualToString:@"SALE"]){
        if([_summary.transactionStatus isEqualToString:@"READY"] || [_summary.transactionStatus isEqualToString:@"PENDING"] || [_summary.transactionStatus isEqualToString:@"COMPLETE"]
           || [_summary.transactionStatus isEqualToString:@"APPROVED"]){
            if(![_summary.transactionStatus isEqualToString:@"APPROVED"]){
                _tipButton.hidden = NO;
            }
            _refundButton.hidden = NO;
            _reversalButton.hidden = NO;
            if(_summary.transactionState == nil){
                _voidButton.hidden = NO;
            } else {
                if(![_summary.transactionState isEqualToString:@"CLOSED"]){
                    _voidButton.hidden = NO;
                }else{
                    _voidHeightConst.constant = 0;
                }
            }
        }
    }
    _tableView.estimatedRowHeight = 40.0;
    _tableView.rowHeight = UITableViewAutomaticDimension;
}

-(void)dismissKeyboard {
    [_reasonField resignFirstResponder];
    [_amountField resignFirstResponder];
    [_tipValue resignFirstResponder];
}

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

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

- (IBAction)refundButtonHandle:(id)sender {
    _refundView.hidden = NO;
}

- (IBAction)tipButtonHandler:(id)sender {
    _tipAdjustmentView.hidden = NO;
}

- (IBAction)cancelButtonHandle:(id)sender {
    _refundView.hidden = YES;
}

- (IBAction)tipCancelButtonHandler:(id)sender {
    _tipAdjustmentView.hidden = YES;
}

- (IBAction)reversalButtonHandle:(id)sender {
    CoreReversal* reversal = [CoreReversal new];
    reversal.uniqueRef = _summary.uniqueRef;
    reversal.deviceType = @"NOMAD";
    reversal.reason = @"reason";
    [[WTPSTerminal singleton] processReversal:reversal];
    [[UiHelper singleton] showLoading:self.view isDeviceSale:NO];
}

- (IBAction)voidButtonHandle:(id)sender {
    UIAlertController * alert = [UIAlertController
                                 alertControllerWithTitle:@"Void the transaction"
                                 message:@"Would you like to void the transaction ?"
                                 preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction* yesButton = [UIAlertAction
                                actionWithTitle:@"Yes"
                                style:UIAlertActionStyleDefault
                                handler:^(UIAlertAction * action) {
                                    CoreRefund* refund = [[CoreRefund alloc] init];
                                    refund.amount = _summary.amount;
                                    refund.reason = @"reason";
                                    refund.uniqueRef = _summary.uniqueRef;
                                    [[WTPSTerminal singleton] processRefund:refund];
                                    [[UiHelper singleton] showLoading:self.view isDeviceSale:NO];
                                }];
    
    UIAlertAction* noButton = [UIAlertAction
                               actionWithTitle:@"No"
                               style:UIAlertActionStyleDefault
                               handler:^(UIAlertAction * action) {
                                   
                               }];
    
    [alert addAction:yesButton];
    [alert addAction:noButton];
    [self presentViewController:alert animated:YES completion:nil];
}

- (NSNumber*)getAmount{
    NSMutableString* amount = [self.amountField.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]];
}

- (NSNumber*)getTipAmount{
    NSMutableString* amount = [self.tipValue.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]];
}

- (IBAction)submitButtonHandle:(id)sender {
    if([_amountField.text isEqualToString:@""]){
        [[UiHelper singleton] showWarning:@"Invalid amount"];
        return;
    }
    if([_reasonField.text isEqualToString:@""]){
        [[UiHelper singleton] showWarning:@"Invalid reason"];
        return;
    }
    CoreRefund* refund = [[CoreRefund alloc] init];
    refund.amount = [self getAmount];
    refund.reason = _reasonField.text;
    refund.uniqueRef = _summary.uniqueRef;
    [[WTPSTerminal singleton] processRefund:refund];
    [[UiHelper singleton] showLoading:self.view isDeviceSale:NO];
}
- (IBAction)tipSubmitButtonHandler:(id)sender {
    if([_tipValue.text isEqualToString:@""]){
        [[UiHelper singleton] showWarning:@"Invalid tip"];
        return;
    }
    
    CoreUpdate* update = [[CoreUpdate alloc] init];
    CoreTip* tipAdjustment = [[CoreTip alloc] init];
    NSNumber* value = [self getTipAmount];
    
    if(_tipTypeSegment.selectedSegmentIndex == 0){
        tipAdjustment.tipType = @"FIXED_AMOUNT";
        tipAdjustment.amount = value;
        
    }else{
        tipAdjustment.tipType = @"PERCENTAGE";
        tipAdjustment.percentage = value;
        tipAdjustment.amount = @([_summary.amount doubleValue] * [value doubleValue] / 100);
    }
    
    update.uniqueRef = _summary.uniqueRef;
    update.tipAdjustment = tipAdjustment;
    
    [[WTPSTerminal singleton] updateTransaction:update];
    [[UiHelper singleton] showLoading:self.view isDeviceSale:NO];
}

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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [tableData count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CardCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"cardCell"];
    
    if (cell == nil) {
        cell = [[CardCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cardCell"];
    }
    
    NSString *summary = [tableData objectAtIndex:indexPath.row];
    NSArray *array = [summary componentsSeparatedByString:@";"];
    cell.labelKey.text = [array objectAtIndex:0];
    cell.labelValue.text = [array objectAtIndex:1];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

-(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;
    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;
    }
    textField.text = [_currencyFormatter stringFromNumber:formatedValue];
    return NO;
}

@end
