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

#import "SearchGroupViewController.h"

#import <SDWebImage/UIImageView+WebCache.h>

#import "ServerAPI.h"
#import "Utilities.h"

#import "SearchGroupTableViewCell.h"
#import "CreateGroupViewController.h"
#import "GroupDetailViewController.h"

@interface SearchGroupViewController ()

@end

@implementation SearchGroupViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.topLayoutGuide attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.viewHeader attribute:NSLayoutAttributeTop multiplier:1 constant:0]];

    [self callRequestToUpdateData];
    
    //register nib for table view
    [self.tableBase registerNib:[UINib nibWithNibName:@"SearchGroupTableViewCell" bundle:nil] forCellReuseIdentifier:@"SearchGroupCell"];
}

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

#pragma mark IBAction

- (IBAction)clickBack:(id)sender {
    [self.navigationController popViewControllerAnimated:true];
}

- (IBAction)clickSearch:(id)sender {
    [self.view endEditing:true];
    [self resetData];
}

- (IBAction)clickCreateGroup:(id)sender {
    CreateGroupViewController * create = [[CreateGroupViewController alloc] init];
    create.createGroupSuccess = ^(GroupObject *object){
        GroupDetailViewController * detail = [[GroupDetailViewController alloc] init];
        [detail setGroup:object];
        [self.navigationController pushViewController:detail animated:true];
    };
    [self.navigationController pushViewController:create animated:true];
}

#pragma mark UITableView Delegate
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SearchGroupTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"SearchGroupCell"];
    GroupObject *object = [_curDataList objectAtIndex:indexPath.row];
    if(object.avatar && ![object.avatar isKindOfClass:[NSNull class]]) {
        [cell.imgAvatar sd_setImageWithURL:[NSURL URLWithString:[Utilities getImageLink:object.avatar]]];
    }
    else {
        [cell.imgAvatar setImage:[UIImage imageNamed:@"avatar_default"]];
    }
    cell.lblName.text       = object.name;
    return cell;
}

-(void) scrollViewDidScroll:(UIScrollView *)scrollView {
    [self.view endEditing:true];
}

-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    GroupDetailViewController * detail = [[GroupDetailViewController alloc] init];
    [detail setGroup:[_curDataList objectAtIndex:indexPath.row]];
    [self.navigationController pushViewController:detail animated:true];
}

#pragma mark UITextField Delegate
-(BOOL) textFieldShouldReturn:(UITextField *)textField {
    [self.view endEditing:true];
    return true;
}

-(BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if(timerSearch != nil) {
        [timerSearch invalidate];
    }
    timerSearch = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(resetData) userInfo:nil repeats:false];
    return true;
}

#pragma mark Private Function
-(void) callRequestToUpdateData {
    [super callRequestToUpdateData];
    
    NSString * token = [[NSUserDefaults standardUserDefaults] stringForKey:kToken];
    MBProgressHUD *hudView = nil;
    if(_curPage == 1 && !self.refreshControl.isRefreshing) {
        hudView = [MBProgressHUD showHUDAddedTo:self.view animated:true];
    }
    [[ServerAPI server] searchGroup:token withKey:self.textFieldSearch.text andPage:_curPage CompletionHandler:^(NSArray *array, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if(hudView != nil) {
                [hudView hideAnimated:true];
            }
        });
        SearchGroupViewController __weak *weakSelf = self;
        [weakSelf updateTableData:array error:error];
    }];
}
@end
