//
//  InvitationListViewController.m
//  kneet
//
//  Created by Jason Lee on 6/12/15.
//  Copyright (c) 2015 ntels. All rights reserved.
//
#import "RequestHandler.h"
#import "LoginModel.h"

#import "CustomTableView.h"
#import "CustomButton.h"
#import "CustomLabel.h"
#import "ImageUtil.h"
#import "UIImageView+WebCache.h"
#import "CustomImageView.h"
#import "CustomAlertView.h"

#import "InvitationAnswerPopupView.h"
#import "LoginViewController.h"

#import "InvitationListViewController.h"
#import "InvitationAnswerViewController.h"

@implementation InvitationTableViewCell
- (void)awakeFromNib {
    self.selectionStyle = UITableViewCellSelectionStyleNone;
    self.backgroundColor = [UIColor clearColor];
}

- (void)didMoveToSuperview {
    _lblJoin.text = NSLocalizedString(@"참여", @"참여");
    _lblReject.text = NSLocalizedString(@"거절", @"거절");
}

@end


@interface InvitationListViewController () <UITableViewDataSource, UITableViewDelegate> {
    NSMutableArray<InvitationModel> *_invitationList;
}
@end


#pragma mark - Class Definition

@implementation InvitationListViewController


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

    [self initUI];
    [self prepareViewDidLoad];
}


- (void)initUI {
    
    [self initTableViewAsDefaultStyle:_tableView];
}

- (void)prepareViewDidLoad {
    
//    [[JDFacade facade] updateLoginInfo:^{
//        _invitationList = [JDFacade facade].loginUser.invitationList;
//        
//        dispatch_async(dispatch_get_main_queue(), ^{
//            [_tableView reloadData];
//        });
//    }];
    [self requestInvitationList];
}

#pragma mark - Main Logic

- (void)requestInvitationList {
    //parameters
    NSString *path = [NSString stringWithFormat:API_GET_HOMEGROUP_MEMBER_INVITATIONS];
    
    [[RequestHandler handler] sendAsyncGetRequestAPIPath:path parameters:nil modelClass:[InvitationListModel class] completion:^(id responseObject) {
        if (!responseObject) {//응답결과가 잘못되었거나 없을 경우,
            return;
        }
        
        InvitationListModel *fetchedInvitationList = (InvitationListModel *) responseObject;
        
        if (fetchedInvitationList && fetchedInvitationList.list) {//API 성공 ,
            _invitationList = fetchedInvitationList.list;
        }
        
        [_tableView reloadData];
        
        if (_invitationList && !_invitationList.count) {
            [self btnCloseTouched:nil];
        }
    } failure:^(id errorObject) {
        JDErrorModel *error = (JDErrorModel *)errorObject;
        [[JDFacade facade] alert:error.errorMessage];
    }];

}

- (void)requestRejectInvitation:(InvitationModel *)invitation {
    //parameters
    NSDictionary *parameter = @{@"homegrp_id": invitation.homegrpId,
                                @"status_code": ksNO};

    NSString *path = [NSString stringWithFormat:API_POST_HOMEGROUP_MEMBER_INVITATIONS];

    [[RequestHandler handler] sendAsyncPostRequestAPIPath:path parameters:parameter modelClass:[JDJSONModel class] completion:^(id responseObject) {
        
        [[JDFacade facade] alert:NSLocalizedString(@"아쉽지만 다음에\n다시 초대할께요", @"아쉽지만 다음에\n다시 초대할께요") completionHander:^{

            [_invitationList removeObject:invitation];
            if (_invitationList.count > 0) {//초대건수가 있으면, 다시 로드함.
                [_tableView reloadData];
            } else {//다음 플로우 진행
                [[JDFacade facade] alertTitle:@"홈 초대 거절" message:@"참여한 홈이 없습니다.\n홈허브에 연결해서 직접 홈을 만들어 보세요" completionHander:^{
                    [self btnCloseTouched:nil];
                }];
            }
        }];
        
    } failure:^(id errorObject) {
        JDErrorModel *error = (JDErrorModel *)errorObject;
        [[JDFacade facade] alert:error.errorMessage];
    }];
}


#pragma mark - UITableView DataSource & Delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

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

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    CGFloat height = 0;
    CGFloat width = IPHONE_WIDTH - 80 - 20;
    CustomLabel *lblTemp = [[CustomLabel alloc] initWithFrame:CGRectMake(0, 0, width, 17)];
    lblTemp.font = [UIFont systemFontOfSize:kUIFontSize01];
    lblTemp.numberOfLines = 0;

    InvitationModel *invitation = _invitationList[indexPath.row];
    NSString *fromNickname = invitation.nickname;
    CGFloat adjustHeight = [CommonUtil getSizeFromString:fromNickname font:lblTemp.font width:width].height;
    adjustHeight = adjustHeight < 20 ? 0 : adjustHeight - 20;

    height = 95 + adjustHeight;
    
    return height;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    InvitationModel *invitation = _invitationList[indexPath.row];

    InvitationTableViewCell *tcell = [tableView dequeueReusableCellWithIdentifier:@"InvitationCellIdentifier"];
    tcell.lblFromNickname.text = invitation.nickname;

    //TODO : crop or set circle background
    [tcell.imgvProfile sd_setImageWithURL:[NSURL URLWithString:invitation.imageFileName] placeholderImage:nil options:SDWebImageRefreshCached];
    
    tcell.lblJoin.value = invitation;
    tcell.lblReject.value = invitation;

    if (!tcell.lblJoin.touchHandler) {
        [tcell.lblJoin addTouchEventHandler:^(id label) {
            [self lblJoinTouched:label];
        }];
    }
    
    if (!tcell.lblReject.touchHandler) {
        [tcell.lblReject addTouchEventHandler:^(id label) {
            [self lblRejectTouched:label];
        }];
    }
    
    return tcell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [super tableView:tableView didSelectRowAtIndexPath:indexPath];
}


#pragma mark - UI Events



- (void)lblJoinTouched:(id)sender {
    CustomLabel *lblJoin = (CustomLabel *)sender;
    InvitationModel *invitation = lblJoin.value;
    
    InvitationAnswerViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"InvitationAnswerViewController" storyboardName:@"Main"];
    vc.invitation = invitation;
    
    if (_invitationList.count > 1) {
        CustomAlertView *alert = [[CustomAlertView alloc] initWithTitle:@"홈 초대 수락"
                                                                message:@"둘리님의 홈에 참여할까요?\n\n한 아이디로는 하나의 홈에만\n참여할 수 있기 때문에\n다른 홈에서 받은 초대는\n자동으로 거절합니다."
                                                                delegate:nil OKButtonTitle:@"확인" cancelButtonTitle:@"취소"];
        [alert showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
            if (buttonIndex == 0) {//OK
                [self presentViewController:vc animated:YES completion:nil];
            }
        }];
    } else {
        [self presentViewController:vc animated:YES completion:nil];
    }
}

- (void)lblRejectTouched:(id)sender {
    CustomLabel *lblReject = (CustomLabel *)sender;
    InvitationModel *invitation = lblReject.value;
    
    [self requestRejectInvitation:invitation];
}


- (IBAction)btnCloseTouched:(id)sender {
    
    [self dismissViewControllerAnimated:YES completion:^{
        if ([[JDFacade facade].currentViewController isKindOfClass:[LoginViewController class]]) {
            LoginViewController *lvc = (LoginViewController *)[JDFacade facade].currentViewController;
            [lvc actionAfterInvitaion];
        }
    }];
}


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

@end
