#import "ReportingViewController.h"

@interface ReportingViewController()<UITabBarControllerDelegate>

@property (weak, nonatomic) IBOutlet UIView *topView;
@property (weak, nonatomic) IBOutlet UILabel *status;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIView *filterView;
@property (weak, nonatomic) IBOutlet UISwitch *openCheckbox;
@property (weak, nonatomic) IBOutlet UISwitch *closeCheckBox;
@property (weak, nonatomic) IBOutlet UIDatePicker *fromDate;
@property (weak, nonatomic) IBOutlet UIDatePicker *toDate;
@property (weak, nonatomic) IBOutlet UIPickerView *itemsPerPage;
@property (weak, nonatomic) IBOutlet UIButton *filterButton;
@property NSArray *optionItemsPerPage;
@property NSNumber *itemsPerPageNumber;

@end


@implementation ReportingViewController
{
    UIColor* color;
    NSMutableArray *tableData;
    TransactionDetailViewController* tansactionDetail;
    UIRefreshControl *refreshControl;
    BOOL isLoading;
    int currentPage;
    BOOL refresh;
    BOOL hasMore;
    UIStoryboard *storyboard;
}

- (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];
    tableData = [[NSMutableArray alloc] init];
    currentPage = 0;
    refreshControl = [[UIRefreshControl alloc] init];
    [refreshControl addTarget:self action:@selector(refresh) forControlEvents:UIControlEventValueChanged];
    [self.tableView addSubview:refreshControl];
    _filterView.hidden = YES;
    hasMore = YES;
    self.optionItemsPerPage = @[@"10",@"25",@"50"];
    [self.itemsPerPage selectRow:1 inComponent:0 animated:YES];
    self.itemsPerPageNumber = @([self.optionItemsPerPage[1] intValue]);
    
    [self refresh];
}

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

- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController{
    if(![viewController.restorationIdentifier isEqualToString:@"reportingViewControllerNavigation"]){
        [[WTPSTerminal singleton] unRegisterCoreAPIRefundListener:self];
        [[WTPSTerminal singleton] unRegisterCoreAPIReversalListener:self];
        [[WTPSTerminal singleton] unRegisterCoreAPIUpdateListener:self];
        [[WTPSTerminal singleton] unRegisterCoreAPIMessageListener:self];
        [[WTPSTerminal singleton] unRegisterCoreAPIReportingListener:self];
    }
}

- (void) refresh{
    refresh = YES;
    currentPage = 0;
    [self loadNextPage];
}

- (void)loadNextPage {
    if (isLoading) return;
    isLoading = YES;
    
    CoreTransactionFilter *filter = [[CoreTransactionFilter alloc] init];
    
    if([self.openCheckbox isOn]){
        if([self.closeCheckBox isOn]){
            filter.state = ALL;
        }else{
            filter.state = OPEN;
        }
    }else if([self.closeCheckBox isOn]){
        filter.state = CLOSED;
    }else{
        filter.state = -1;
    }
    
    filter.startDate = [Util formatDateToServerFormat:self.fromDate.date];
    filter.endDate = [Util formatDateToServerFormat:self.toDate.date];
    filter.resultsPerPage = self.itemsPerPageNumber;
    
    [[WTPSTerminal singleton] getTransactions:[NSNumber numberWithInt:currentPage] usingFilter:filter];
}

- (void) setTheme{
    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)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];
    }
}

#pragma mark ------------- Filter --------------

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    return self.optionItemsPerPage.count;
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    return self.optionItemsPerPage[row];
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    self.itemsPerPageNumber = @([self.optionItemsPerPage[row] intValue]);
}

- (IBAction)filterOpenHandle:(id)sender {
    _filterView.alpha = 0;
    _filterView.hidden = NO;
    [UIView animateWithDuration:0.6 animations:^{
        _filterView.alpha = 1;
    } completion: ^(BOOL finished) {
    }];
}

- (IBAction)filterCloseHandle:(id)sender {
    [UIView animateWithDuration:0.6 animations:^{
        _filterView.alpha = 0;
    } completion: ^(BOOL finished) {
        _filterView.hidden = YES;
    }];
}

- (IBAction)filterButtonHandle:(id)sender {
    [self filterCloseHandle:nil];
    [self refresh];
}

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

- (void)filterTransactions:(CoreTransactionFilter *)filter {
    [self dismissViewControllerAnimated:YES completion:nil];
    [[WTPSTerminal singleton] getTransactions:[NSNumber numberWithInt:1] usingFilter:filter];
    [[UiHelper singleton] showLoading:self.view isDeviceSale:NO];
}

#pragma mark ------------- TableView --------------

- (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"];
    }
    
    CoreTransactionSummary *summary = [tableData objectAtIndex:indexPath.row];
    cell.name.text = [summary.cardHolderName isEqual:[NSNull null]] ? @"" : summary.cardHolderName;
    cell.amount.text = [getCurrencyData(summary.currency)[2] stringByAppendingString:[summary.amount stringValue]];
    cell.cardNumber.text = summary.cardNumber;
    cell.date.text = summary.transactionDate;
    
    if (summary.transactionState == nil){
        if([summary.transactionType isEqualToString:@"SALE"] && [summary.transactionStatus isEqualToString:@"APPROVED"]){
            cell.transactionStatusView.backgroundColor = UIColorFromRGB(0x27AE60);
        } else {
            cell.transactionStatusView.backgroundColor = UIColorFromRGB(0xE74C3C);
        }
    } else {
        if([summary.transactionType isEqualToString:@"SALE"] && ![summary.transactionStatus isEqualToString:@"READY"] &&
           ![summary.transactionStatus isEqualToString:@"PENDING"]&&
           ![summary.transactionStatus isEqualToString:@"COMPLETE"]){
            cell.transactionStatusView.backgroundColor = UIColorFromRGB(0xE74C3C);
        } else {
            if([summary.transactionStatus isEqualToString:@"READY"]){
                cell.transactionStatusView.backgroundColor = UIColorFromRGB(0x2980B9);
            } else if ([summary.transactionStatus isEqualToString:@"PENDING"]){
                cell.transactionStatusView.backgroundColor = UIColorFromRGB(0xE67E22);
            } else {
                cell.transactionStatusView.backgroundColor = UIColorFromRGB(0x27AE60);
            }
        }
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    BOOL lastItemReached = [summary isEqual:[tableData lastObject]];
    if (lastItemReached && !isLoading && hasMore){
        currentPage = currentPage +1;
        [self loadNextPage];
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 80;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    CoreTransactionSummary *summary = [tableData objectAtIndex:indexPath.row];
    UINavigationController *settings = [storyboard instantiateViewControllerWithIdentifier:@"transactionDetailNavigation"];
    tansactionDetail = [[settings viewControllers] objectAtIndex:0];
    tansactionDetail.summary = summary;
    [self presentViewController:settings animated:YES completion:nil];
}

- (void) stopRefreshing{
    if([refreshControl isRefreshing]){
        [refreshControl endRefreshing];
    }
}

#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];
    [_status setText:errorValue];
    [self stopRefreshing];
    [[UiHelper singleton] showError:errorValue];
}

/*!
 * Returns URL which needs to be used to sign in into SelfCare System in response to requestSecuredUrl method.
 * @param url
 */
-(void)onLoginUrlRetrieved:(NSString *)url{
    NSLog(@"onLoginUrlRetrieved");
    [_status setText:@"onLoginUrlRetrieved"];
    [[UiHelper singleton] hideLoading];
}

/*!
 * 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];
    [[UiHelper singleton] toastMessage:messageValue];
    [_status 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");
    [_status setText:@"REFUND RESPONSE"];
    [[UiHelper singleton] hideLoading];
    if (tansactionDetail.presentingViewController != nil) {
        [tansactionDetail dismissViewControllerAnimated:YES completion:nil];
    }
    UINavigationController *card= [storyboard instantiateViewControllerWithIdentifier:@"ReceiptViewControllerNavigation"];
    ReceiptViewController *receipt = [[card viewControllers] objectAtIndex:0];
    receipt.coreResponse = refundResponse;
    [self presentViewController:card animated:YES completion:nil];
}

/*!
 * Returns CoreTransactions object which consists of the list with the last 10 transactions in response to getTransactions method.
 * @param transaction contains CoreTransactions object retrieved from the server
 */
-(void)onTransactionListResponse:(CoreTransactions*)transaction{
    NSLog(@"onTransactionListResponse");
    [_status setText:@"onTransactionListResponse"];
    isLoading = NO;
    if([transaction.transactionSummary count] == 0){
        hasMore = NO;
        return;
    } else {
        hasMore = YES;
    }
    [[UiHelper singleton] hideLoading];
    [self stopRefreshing];
    if(refresh){
        refresh = NO;
        [tableData removeAllObjects];
        [self.tableView reloadData];
    }
    NSMutableArray *finalArray = transaction.transactionSummary;
    for (int i=0; i<[finalArray count] ; i++) {
        CoreTransactionSummary *summary = [finalArray objectAtIndex:i];
        [tableData addObject:summary];
    }
    
    if([transaction.transactionSummary count] < [self.itemsPerPageNumber intValue]){
        hasMore = NO;
    }
    if([[[WTPSTerminal singleton] getSettings].features objectForKey:@"payconexSdk"] != nil){
        hasMore = NO;
    }
    
    [self.tableView reloadData];
}

/*!
 * This method is called after reversal has been processed.
 * @param sale contains reversal object retrieved from the server
 */
-(void) onReversalRetrieved:(CoreResponse*)reversalResponse{
    NSLog(@"onReversalRetrieved");
    [_status setText:@"REVERSAL RESPONSE"];
    [[UiHelper singleton] hideLoading];
    if (tansactionDetail.presentingViewController != nil) {
        [tansactionDetail dismissViewControllerAnimated:YES completion:nil];
    }
    UINavigationController *card= [storyboard instantiateViewControllerWithIdentifier:@"ReceiptViewControllerNavigation"];
    ReceiptViewController *receipt = [[card viewControllers] objectAtIndex:0];
    receipt.coreResponse = reversalResponse;
    [self presentViewController:card animated:YES completion:nil];
}

/**
 * This method is called after updating transaction in response to updateTransaction method.
 *
 * @param response contains response object
 */
- (void)onRequestUpdateResponse:(CoreResponse *)response{
    [[UiHelper singleton] hideLoading];
    [[UiHelper singleton] showSuccess:@"Transaction updated" withMessage:@"Transaction updated successfully"];
}

@end
