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

#import "GroupDetailViewController.h"
#import <SDWebImage/UIImageView+WebCache.h>

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

@interface GroupDetailViewController ()

@end

@implementation GroupDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.topLayoutGuide attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.viewHeader attribute:NSLayoutAttributeTop multiplier:1 constant:0]];
    isMemberList = false;
    //register nib for table view
    [self.tableBase registerNib:[UINib nibWithNibName:@"SNSRecentTopicTableViewCell" bundle:nil] forCellReuseIdentifier:@"RecentTopicCell"];
    if(_curGroup != nil) {
        [self requestGroupDetail];
    }
    // Do any additional setup after loading the view from its nib.
}

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

- (void) setGroup : (GroupObject *) object {
    _curGroup = object;
}

- (void)setupView {
    if(_curGroup != nil) {
        if(self.imgAva != nil && _curGroup.avatar && ![_curGroup.avatar isKindOfClass:[NSNull class]]) {
            [self.imgAva sd_setImageWithURL:[NSURL URLWithString:[Utilities getImageLink:_curGroup.avatar]]];
        }
        if(self.lblGrpName != nil) {
            [self.lblGrpName setText:_curGroup.name];
        }
        if(self.btJoinGrp != nil) {
            [self.btJoinGrp setHidden:false];
        }
        NSString *mode = @"";
        NSString *goalText = [NSString stringWithFormat:@"%@\n", _curGroup.goal];
        if(_curGroup.runMode || _curGroup.walkMode || _curGroup.bikeMode) {
            goalText = [goalText stringByAppendingString:@"１日　目標 "];
        }
        if(_curGroup.runMode) {
            mode = [mode stringByAppendingString:NSLocalizedString(@"lifelog.grDetail.mode.running", nil)];
            mode = [mode stringByAppendingString:@"\n"];
            goalText = [goalText stringByAppendingFormat:@"RUN %dm, ", _curGroup.runGoal];
        }
        if(_curGroup.walkMode) {
            mode = [mode stringByAppendingString:NSLocalizedString(@"lifelog.grDetail.mode.walking", nil)];
            mode = [mode stringByAppendingString:@"\n"];
            goalText = [goalText stringByAppendingFormat:@"WALK %dm, ", _curGroup.walkGoal];
        }
        if(_curGroup.bikeMode) {
            mode = [mode stringByAppendingString:NSLocalizedString(@"lifelog.grDetail.mode.bike", nil)];
            mode = [mode stringByAppendingString:@"\n"];
            goalText = [goalText stringByAppendingFormat:@"BIKE %dm, ", _curGroup.bikeGoal];
        }
        if(_curGroup.stepMode) {
            mode = [mode stringByAppendingString:NSLocalizedString(@"lifelog.grDetail.mode.step", nil)];
            mode = [mode stringByAppendingString:@"\n"];
        }
        if(_curGroup.beginMode) {
            mode = [mode stringByAppendingString:NSLocalizedString(@"lifelog.grDetail.mode.begin", nil)];
            mode = [mode stringByAppendingString:@"\n"];
        }
        if(_curGroup.gymMode) {
            mode = [mode stringByAppendingString:NSLocalizedString(@"lifelog.grDetail.mode.gym", nil)];
            mode = [mode stringByAppendingString:@"\n"];
        }
        NSRange range = [mode rangeOfString:@"\n" options:NSBackwardsSearch];
        if(range.length > 0) {
            mode = [mode stringByReplacingOccurrencesOfString:@"\n" withString:@"" options:NSBackwardsSearch range:range];
        }
        range = [goalText rangeOfString:@", " options:NSBackwardsSearch];
        if(range.length > 0) {
            goalText = [goalText stringByReplacingOccurrencesOfString:@", " withString:@"" options:NSBackwardsSearch range:range];
        }
        [self.lbbGrpActiveMode setText:mode];
        [self.lblGrpGoal setText:goalText];
    }
}

- (void) requestGroupDetail {
    NSString * token = [[NSUserDefaults standardUserDefaults] stringForKey:kToken];
    MBProgressHUD *hudView = [MBProgressHUD showHUDAddedTo:self.view animated:true];
    [[ServerAPI server] getGroupDetail:token withGroupID:_curGroup.groupID CompletionHandler:^(GroupObject *object, NSError *error) {
        GroupDetailViewController __weak *weakSelf = self;
        [_curGroup updateDate:object];
        dispatch_async(dispatch_get_main_queue(), ^{
            [hudView hideAnimated:true];
            [weakSelf setupView];
            [weakSelf callRequestToUpdateData];
        });
    }];
}

#pragma mark IBAction

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

- (IBAction)clickSwitch:(AutoTransButton *)sender {
    isMemberList = !isMemberList;
    if(isMemberList) {
        [sender setTitle:NSLocalizedString(@"lifelog.grDetail.bt.viewTweet", nil) forState:UIControlStateNormal];
    }
    else {
        [sender setTitle:NSLocalizedString(@"lifelog.grDetail.bt.viewMem", nil) forState:UIControlStateNormal];
    }
    [sender setUserInteractionEnabled:false];
    [self resetData];
}

- (IBAction)clickJoin:(AutoTransButton *)sender {
    NSString * token = [[NSUserDefaults standardUserDefaults] stringForKey:kToken];
    MBProgressHUD *hudView = [MBProgressHUD showHUDAddedTo:self.view animated:true];
    [[ServerAPI server] requestJoinGroup:token groupID:_curGroup.groupID CompletionHandler:^(NSError *error){
        GroupDetailViewController __weak *weakSelf = self;
        dispatch_async(dispatch_get_main_queue(), ^{
            [hudView hideAnimated:true];
            if(error == nil) {
                _curGroup.isJoin = true;
                [weakSelf.btJoinGrp setHidden:_curGroup.isJoin];
                [Utilities showMessage:@"Join successfully" withViewController:weakSelf];
            }
        });
    }];

}



#pragma mark UITableView Delegate
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SNSRecentTopicTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"RecentTopicCell"];
    if(isMemberList) {
        MemberObject *object = [_curDataList objectAtIndex:indexPath.row];
        [cell setMemberData:object];
    }
    else {
        TweetObject *object = [_curDataList objectAtIndex:indexPath.row];
        [cell setTweetsData:object];
    }
  
    return cell;
}

#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];
    }
    if(isMemberList) {
        [[ServerAPI server] requestMemberList:token groupID:_curGroup.groupID withPage:_curPage CompletionHandler:^(NSArray *array, NSError *error){
            dispatch_async(dispatch_get_main_queue(), ^{
                if(hudView != nil) {
                    [hudView hideAnimated:true];
                }
            });
            GroupDetailViewController __weak *weakSelf = self;
            [weakSelf updateTableData:array error:error];
            [weakSelf.btSwitch setUserInteractionEnabled:true];
        }];
    }
    else {
        [[ServerAPI server] requestTweetsList:token groupID:_curGroup.groupID withPage:_curPage CompletionHandler:^(NSArray *array, NSError *error){
            dispatch_async(dispatch_get_main_queue(), ^{
                if(hudView != nil) {
                    [hudView hideAnimated:true];
                }
            });
            GroupDetailViewController __weak *weakSelf = self;
            [weakSelf updateTableData:array error:error];
            [weakSelf.btSwitch setUserInteractionEnabled:true];
        }];
    }
}

@end
