//
//  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 "CustomButton.h"
#import "CustomLabel.h"

#import "InvitationListViewController.h"

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


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

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

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

@interface InvitationListViewController () <UITableViewDataSource, UITableViewDelegate> {
    NSMutableArray<InvitationModel> *_invitationList;
    UIImage *_bgCellImage1, *_bgCellImage2;
    InvitationAnswerPopupView *_apopup;
}
@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 {
    

    //set tableview option
    _tableView.delegate = self;
    _tableView.dataSource = self;

    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.backgroundColor = [UIColor clearColor];

    _tableView.tableFooterView = [[UIView alloc] init]; //this call table events;

    UIEdgeInsets insets = UIEdgeInsetsMake(4, 4, 4, 4);
    _bgCellImage1 = [ImageUtil resizableImageWithCapInsets:insets resizingMode:UIImageResizingModeStretch img:[UIImage imageNamed:@"tp_01_img_list_bg_02"]];
    _bgCellImage2 = [ImageUtil resizableImageWithCapInsets:insets resizingMode:UIImageResizingModeStretch img:[UIImage imageNamed:@"tp_01_img_list_bg_01"]];
    
}

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

#pragma mark - Main Logic

- (void)requestJoinInvitation:(InvitationModel *)invitation {
    //parameters
    NSDictionary *parameter = @{@"homegrp_id": invitation.homegrpId,
                                @"authorization_reply": invitation.sdate,
                                @"target_email": invitation.targetEmail,
                                @"status_code": ksYES};

    NSString *path = [NSString stringWithFormat:API_POST_HOMEGROUP_MEMBER_STAT];

    [[RequestHandler handler] sendAsyncPostRequestAPIPath:path parameters:parameter modelClass:[JDJSONModel class] completion:^(id responseObject) {
        if (!responseObject) {//응답결과가 잘못되었거나 없을 경우,
            return;
        }

        JDJSONModel *result = (JDJSONModel *) responseObject;

        if (result) {//API 성공 ,
            [_invitationList removeObject:invitation];

            NSString *msg = [NSString stringWithFormat:NSLocalizedString(@"축하합니다!\n[%@] 멤버가 되었습니다.", @"축하합니다!\n[%@] 멤버가 되었습니다."), invitation.homegrpName];
            
            [[JDFacade facade] alert:msg completionHander:^{
                [self gotoNextScreenOnFlow];
            }];
        }
    } failure:^(id errorObject) {//답변이 틀린 경우,
        JDErrorModel *error = (JDErrorModel *)errorObject;

        if ([error.errorCode isEqualToString:@"400-102"]) {//답변이
            if ([error.errorCount integerValue] < 3) {//답변이 1,2회 틀린 경우,
                [[JDFacade facade] alert:error.errorMessage completionHander:^{
                    [self popInvitationAnswer:invitation];
                }];
            } else {//답변이 3회 틀린 경우,
                [[JDFacade facade] alert:error.errorMessage completionHander:^{
                    [_invitationList removeObject:invitation];

                    if (_invitationList.count > 0) {//초대건수가 있으면, 다시 로드함.
                        [_tableView reloadData];
                    } else {//다음 플로우 진행
                        [self gotoNextScreenOnFlow];
                    }
                }];
            }
        } else {
            [[JDFacade facade] alert:error.errorMessage];
        }
    }];
}

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

    NSString *path = [NSString stringWithFormat:API_POST_HOMEGROUP_MEMBER_STAT];

    [[RequestHandler handler] sendAsyncPostRequestAPIPath:path parameters:parameter modelClass:[JDJSONModel class] completion:^(id responseObject) {
        if (!responseObject) {//응답결과가 잘못되었거나 없을 경우,
            return;
        }

        JDJSONModel *result = (JDJSONModel *) responseObject;

        if (result) {//API 성공 ,
            [[JDFacade facade] alert:NSLocalizedString(@"아쉽지만 다음에\n다시 초대할께요", @"아쉽지만 다음에\n다시 초대할께요") completionHander:^{

                [_invitationList removeObject:invitation];
                if (_invitationList.count > 0) {//초대건수가 있으면, 다시 로드함.
                    [_tableView reloadData];
                } else {//다음 플로우 진행
                    [self gotoNextScreenOnFlow];
                }
            }];
        }
    } failure:^(id errorObject) {
        JDErrorModel *error = (JDErrorModel *)errorObject;
        [[JDFacade facade] alert:error.errorMessage];
    }];
}


- (void)gotoNextScreenOnFlow {
    //다음 화면으로 진행 - FIXME : 
    if ([self.presentingViewController isKindOfClass:[UINavigationController class]]) {
        [[JDFacade facade] gotoWishMenu:KNMenuIdDashboard];
    } else {
        LoginViewController *lvc = [[JDFacade facade] viewControllerOnPresentingViewController:self viewControllerClass:[LoginViewController class]];
        if ([lvc isKindOfClass:[LoginViewController class]]) {//로그인일 경우,
            [lvc actionAfterInvitaion];
        }        
    }
}

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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSInteger count = 1;

    if (section == 1) {
        count = _invitationList.count;
    }
    return count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat height = 0;
    if (indexPath.section == 0) {
        
        CGFloat width = IPHONE_WIDTH - 40;
        CustomLabel *lblDesc = [[CustomLabel alloc] initWithFrame:CGRectMake(0, 0, width, 35)];
        lblDesc.font = [UIFont systemFontOfSize:kUIFontSize01];
        lblDesc.numberOfLines = 0;
        
        NSString *desc = [NSString stringWithFormat:NSLocalizedString(@"[%@]님을 기다리는 사람이 있습니다\n홈에 참여해서 함께 장치를 제어해보세요", @"[%@]님을 기다리는 사람이 있습니다\n홈에 참여해서 함께 장치를 제어해보세요"),  [JDFacade facade].loginUser.nickname];
        CGFloat adjustHeight = [CommonUtil getSizeFromString:desc font:lblDesc.font width:width].height;
        adjustHeight = adjustHeight < 35 ? 0 : adjustHeight - 35;

        height = 160 + adjustHeight;

    } else if (indexPath.section == 2) {//action
        height = 100;
    } else if (indexPath.section == 1) {//calculate

        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 *invitationMsg = [NSString stringWithFormat:NSLocalizedString(@"[%@]에 초대합니다", @"[%@]에 초대합니다"), invitation.homegrpName];
        CGFloat adjustHeight = [CommonUtil getSizeFromString:invitationMsg font:lblTemp.font width:width].height;
        adjustHeight = adjustHeight < 17 ? 0 : adjustHeight - 17;

        height = 150 + adjustHeight;
    }
    return height;
}

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

    NSInteger section = indexPath.section;
    UITableViewCell *cell = nil;

    if (section == 0) {//title
        InvitationTitleViewCell *tcell = [tableView dequeueReusableCellWithIdentifier:@"TitleCellIdentifier"];
        tcell.lblTitle.text = NSLocalizedString(@"초대받은 홈에 참여해보세요!", @"초대받은 홈에 참여해보세요!");
        tcell.lblDesc.text = [NSString stringWithFormat:NSLocalizedString(@"[%@]님을 기다리는 사람이 있습니다\n홈에 참여해서 함께 장치를 제어해보세요", @"[%@]님을 기다리는 사람이 있습니다\n홈에 참여해서 함께 장치를 제어해보세요"), [JDFacade facade].loginUser.nickname];
        
        cell = tcell;

    } else if (section == 2) {//action
        InvitationActionCell *tcell = [tableView dequeueReusableCellWithIdentifier:@"ActionCellIdentifier"];
        
        [tcell.btnLater setTitle:NSLocalizedString(@"나중에 다시보기", @"나중에 다시보기") forState:UIControlStateNormal];
        if (![tcell.btnLater actionsForTarget:self forControlEvent:UIControlEventTouchUpInside]) {
            [tcell.btnLater addTarget:self action:@selector(btnLaterTouched:) forControlEvents:UIControlEventTouchUpInside];
        }

        cell = tcell;
    } else if (section == 1) {//invitation

        InvitationModel *invitation = _invitationList[indexPath.row];

        InvitationTableViewCell *tcell = [tableView dequeueReusableCellWithIdentifier:@"CellIdentifier"];
        tcell.lblTitle.text = [NSString stringWithFormat:NSLocalizedString(@"초대자: %@", @"초대자: %@"), invitation.nickname];
        tcell.lblDesc.text = [NSString stringWithFormat:NSLocalizedString(@"[%@]에 초대합니다", @"[%@]에 초대합니다"), invitation.homegrpName];

        [tcell.btnJoin setTitle:NSLocalizedString(@"참여", @"참여") forState:UIControlStateNormal];
        [tcell.btnReject setTitle:NSLocalizedString(@"거절", @"거절") forState:UIControlStateNormal];
        
        tcell.btnJoin.value = invitation;
        tcell.btnReject.value = invitation;

        if (![tcell.btnJoin actionsForTarget:self forControlEvent:UIControlEventTouchUpInside]) {
            [tcell.btnJoin addTarget:self action:@selector(btnJoinTouched:) forControlEvents:UIControlEventTouchUpInside];
        }

        if (![tcell.btnReject actionsForTarget:self forControlEvent:UIControlEventTouchUpInside]) {
            [tcell.btnReject addTarget:self action:@selector(btnRejectTouched:) forControlEvents:UIControlEventTouchUpInside];
        }

        cell = tcell;

        //set background image
        if (indexPath.row % 2 == 1) {
            cell.backgroundView = [[UIImageView alloc] initWithImage:_bgCellImage1];
        } else {
            cell.backgroundView = [[UIImageView alloc] initWithImage:_bgCellImage2];
        }
    }

    return cell;
}

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


- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {

    // Remove seperator inset
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }

    // Prevent the cell from inheriting the Table View's margin settings
    if ([cell respondsToSelector:@selector(setPreservesSuperviewLayoutMargins:)]) {
        [cell setPreservesSuperviewLayoutMargins:NO];
    }

    // Explictly set your cell's layout margins
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}



#pragma mark - UI Events

- (void)popInvitationAnswer:(InvitationModel *)invitation {
    //pop
    if (!_apopup) {
        _apopup = [[InvitationAnswerPopupView alloc] initFromNib];
    }
    _apopup.invitation = invitation;
    [_apopup showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
        if (buttonIndex == 0) {//OK
            invitation.sdate = _apopup.selectedDate;
            [self requestJoinInvitation:invitation];
        }
    }];
}

- (void)btnJoinTouched:(id)sender {
    CustomButton *btnJoin = (CustomButton *)sender;
    InvitationModel *invitation = btnJoin.value;

    [self popInvitationAnswer:invitation];
}

- (void)btnRejectTouched:(id)sender {
    CustomButton *btnReject = (CustomButton *)sender;
    InvitationModel *invitation = btnReject.value;

    [self requestRejectInvitation:invitation];
}

- (void)btnLaterTouched:(id)sender {
    [self gotoNextScreenOnFlow];
}


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

@end
