//
//  BaseTableViewController.m
//  LifeLog
//
//  Created by nvtu on 8/11/17.
//  Copyright © 2017 PhongNV. All rights reserved.
//

#import "BaseTableViewController.h"
#import "Utilities.h"

@interface BaseTableViewController ()

@end

@implementation BaseTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _firstTime = false;
    _curPage   = 1;
    _isEndOfResult = false;
    _isDisableLoadMore = false;
    _curDataList = [[NSMutableArray alloc] init];
    self.refreshControl = [[UIRefreshControl alloc] init];
    [self.refreshControl addTarget:self action:@selector(refreshTable) forControlEvents:UIControlEventValueChanged];
    [self.tableBase addSubview:self.refreshControl];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void) callRequestToUpdateData {
    _isLoading = true;
}

-(void) resetData {
    _isLoading = false;
    _isEndOfResult = false;
    _firstTime = false;
    _curPage = 1;
    [_curDataList removeAllObjects];
    [self.tableBase reloadData];
    [self callRequestToUpdateData];
}

-(void) refreshTable {
    [self resetData];
}

-(void) updateTableData : (NSArray *) array error: (NSError *) error {
    BaseTableViewController __weak *weakSelf = self;
    _isLoading = false;
    _firstTime = true;
    if(self.refreshControl != nil) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.refreshControl endRefreshing];
        });
    }
    if(error == nil) {
        if(_curPage == 1) {
            [_curDataList removeAllObjects];
        }
        if(array.count != 0) {
            [_curDataList addObjectsFromArray:array];
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.tableBase reloadData];
            });
        }
        else {
            if(_curPage != 1) {
                _isEndOfResult = true;
                _curPage -= 1;
            }
            else {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [weakSelf.tableBase reloadData];
                });
            }
        }
    }
    else {
        _curPage = MAX(1, _curPage - 1);
        dispatch_async(dispatch_get_main_queue(), ^{
            NSString *message = [error.userInfo objectForKey:@"message"];
            [Utilities showErrorMessage:message withViewController:weakSelf];
        });
    }
}

#pragma mark UITableView Delegate
- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
    if((_curDataList == nil || _curDataList.count == 0) && _firstTime) {
        UILabel * noDataLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, tableView.frame.size.height)];
        noDataLabel.text            = @"No data available";
        noDataLabel.backgroundColor = [UIColor clearColor];
        noDataLabel.textColor       = [UIColor whiteColor];
        noDataLabel.textAlignment   = NSTextAlignmentCenter;
        tableView.backgroundView    = noDataLabel;
        tableView.backgroundView.layer.zPosition -= 1;
        return 0;
    }
    tableView.backgroundView = nil;
    return 1;
}

- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _curDataList.count;
}

- (void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger lastRowIndex = [tableView numberOfRowsInSection:0] - 1;
    if (indexPath.row == lastRowIndex) {
        // This is the last cell
        if(!_isLoading && !_isDisableLoadMore) {
            _curPage += 1;
            [self callRequestToUpdateData];
        }
    }
}
@end
