//
//  ICRStoreListViewController.m
//  XFFruit
//
//  Created by Xummer on 4/6/15.
//  Copyright (c) 2015 Xummer. All rights reserved.
//

#import "ICRStoreListViewController.h"

#import "ICRStore.h"
#import "IBTUISearchBar.h"

static NSString *StoreListCellIdentifier = @"StoreListCell";

@interface ICRStoreListViewController ()
<
    UITableViewDataSource,
    UITableViewDelegate,
    UISearchBarDelegate,
    UISearchDisplayDelegate
>
@property (strong, nonatomic) IBTTableView *m_tableView;
@property (strong, nonatomic) NSArray *m_arrStores;
@property (strong, nonatomic) IBTUISearchBar *m_searchBar;
@property (strong, nonatomic) NSArray *m_searchResult;
@property (strong, nonatomic) UISearchDisplayController *m_searchDisplayCtr;

@end

@implementation ICRStoreListViewController

#pragma mark - Life Cycle
- (instancetype)initWithBHaveToChooseOne:(BOOL)bHaveTo {
    self = [super init];
    if (!self) {
        return nil;
    }
    
    self.bNotAutoAddCancelButton = bHaveTo;
    
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
        
    [self initTableView];
    [self fetchStoreList];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self doHTTPGetStoreList];
}

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

#pragma mark - Private Method
- (void)initTableView {
    
    CGRect frame = self.view.bounds;
    frame.size.height = IBT_SEARCH_BAR_HEIGHT;
    self.m_searchBar = [[IBTUISearchBar alloc] initWithFrame:frame];
    _m_searchBar.placeholder = [IBTCommon localizableString:@"Search"];
    _m_searchBar.sbDelegate = self;
    
    self.m_tableView =
    [[IBTTableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    [_m_tableView autoresizingWithStrechFullSize];
    
    [_m_tableView registerClass:[IBTTableViewCell class]
         forCellReuseIdentifier:StoreListCellIdentifier];
    _m_tableView.tableHeaderView = _m_searchBar;
    
    _m_tableView.dataSource = self;
    _m_tableView.delegate = self;
    
    [self.view addSubview:_m_tableView];
    
    self.m_searchDisplayCtr = [[UISearchDisplayController alloc] initWithSearchBar:_m_searchBar contentsController:self];
    _m_searchDisplayCtr.delegate = self;
    _m_searchDisplayCtr.searchResultsDataSource = self;
    _m_searchDisplayCtr.searchResultsDelegate = self;
    
}

- (void)configureTableView:(UITableView *)tableView {
    
    tableView.frame = self.view.frame;
    
    [tableView registerClass:[IBTTableViewCell class]
      forCellReuseIdentifier:StoreListCellIdentifier];
    
    UIView *tableFooterViewToGetRidOfBlankRows = [[UIView alloc] initWithFrame:CGRectZero];
    tableFooterViewToGetRidOfBlankRows.backgroundColor = [UIColor clearColor];
    tableView.tableFooterView = tableFooterViewToGetRidOfBlankRows;
}

- (void)doHTTPGetStoreList {
    
    __weak typeof(self)weakSelf = self;
    void(^succ)(id) = ^(id data) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        [strongSelf fetchStoreList];
    };
    
    void(^fail)(id) = ^(id data) {
        [IBTLoadingView showTips:data];
    };
    
    ICRHTTPController *httpCtrl = [ICRHTTPController sharedController];
    [httpCtrl doGetStoreListFromUpdateTime:0 position:0 size:20
                                   success:succ
                                   failure:fail];
}

- (void)fetchStoreList {
    ICRDatabaseFetchBlock fetchBlk = ^FMResultSet *(FMDatabase *db) {
        NSString * sql = [NSString stringWithFormat:@"SELECT * FROM %@ ORDER BY %@", [ICRStore TableName], @"uuid"];
        return [db executeQuery:sql];
    };
    
    __weak typeof(self)weakSelf = self;
    ICRDatabaseFetchResultsBlock fetchResultsBlk = ^(NSArray *fetchedObjects) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        strongSelf.m_arrStores = fetchedObjects;
        [strongSelf.m_tableView reloadData];
    };
    
    ICRDataBaseController *dbCtrl = [ICRDataBaseController sharedController];
    [dbCtrl runFetchForClass:[ICRStore class]
                  fetchBlock:fetchBlk
           fetchResultsBlock:fetchResultsBlk];
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView
 numberOfRowsInSection:(NSInteger)section
{
    if (tableView == self.m_tableView) {
        return [_m_arrStores count];
    } else {
        return [_m_searchResult count];
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell =
    [tableView dequeueReusableCellWithIdentifier:StoreListCellIdentifier
                                    forIndexPath:indexPath];
    
    [self configureCell:cell forRowAtIndexPath:indexPath inTableview:tableView];
    
    return cell;
}

- (void)configureCell:(UITableViewCell *)cell
    forRowAtIndexPath:(NSIndexPath *)indexPath
          inTableview:(UITableView *)tableView
{
    ICRStore *store = nil;
    if (tableView == _m_tableView) {
        store = _m_arrStores[ indexPath.row ];
    } else {
        store = _m_searchResult[ indexPath.row ];
    }
    
    cell.textLabel.textAlignment = NSTextAlignmentCenter;
    cell.textLabel.textColor = [UIColor grayColor];
    cell.textLabel.text = store.name;
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if ([_m_delegate respondsToSelector:@selector(storeListViewCtrl:didSelectedStore:)]) {
        if (tableView == _m_tableView) {
            [_m_delegate storeListViewCtrl:self didSelectedStore:_m_arrStores[ indexPath.row ]];
        } else
        {
            [_m_delegate storeListViewCtrl:self didSelectedStore:_m_searchResult[ indexPath.row ]];
        }
        
    }
    else {
        [self disMissSelf];
    }
}

#pragma mark UISearchDisplayDelegate

- (void)searchDisplayController:(UISearchDisplayController *)controller didLoadSearchResultsTableView:(UITableView *)tableView {
    [self configureTableView:tableView];
}

- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString {
    
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name BEGINSWITH[cd] %@", searchString];
    self.m_searchResult = [self.m_arrStores filteredArrayUsingPredicate:predicate];
    
    return YES;
}

@end
