//
//  HomeMemberViewController.m
//  kneet
//
//  Created by Jason Lee on 6/15/15.
//  Copyright (c) 2015 ntels. All rights reserved.
//

#import "RequestHandler.h"
#import "LoginModel.h"

#import "CustomButton.h"
#import "CustomLabel.h"
#import "CustomLabelButton.h"
#import "CustomImageView.h"
#import "CustomCheckBox.h"
#import "CustomAlertView.h"
#import "UIImageView+WebCache.h"
#import "UIButton+WebCache.h"


#import "HomeMemberViewController.h"
#import "JYPullToRefreshController.h"

#define kfMemberTableViewCellHeight 100.0f

@interface HomeMemberCollectionCell () {
    
}

@property (weak, nonatomic) NSIndexPath *indexPath;

@end


@implementation HomeMemberCollectionCell

- (void)awakeFromNib {
    _chkSelect.hidden = YES;
}

@end

@implementation HomeMemberAddCollectionCell

@end

@implementation HomeMemberCollectionFooterView

- (void)awakeFromNib {

}

@end




@interface HomeMemberViewController () <UICollectionViewDelegate, UICollectionViewDataSource> {
    NSArray<HomeMemberModel> *_memberList;
    
    BOOL _isNotFirstLoading, _isDeleteMode;
    NSInteger _deviceFlag;
    NSString *_masterNickname;
}

@property (strong, nonatomic) JYPullToRefreshController *refreshController;

@end


#pragma mark - Class Definition

@implementation HomeMemberViewController


- (void)viewDidLoad {
    [super viewDidLoad];

    [self initProperties];
    [self initUI];
}

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

    [self prepareViewDidLoad];
}

- (void)initProperties {
    _deviceFlag = IS_IPHONE_6P ? 3 : 2;
}

- (void)initUI {

    //set tableview option
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.backgroundColor = kUIBgColor04;
    _collectionView.alwaysBounceVertical = YES;
    
    [self setThingsPopoverOptions];
    
     [self initRefreshController];
}

- (void)initRefreshController {
    //set refresh controls
    __weak typeof(self) weakSelf = self;
    self.refreshController = [[JYPullToRefreshController alloc] initWithScrollView:self.collectionView];
    self.refreshController.pullToRefreshHandleAction = ^{
        [weakSelf requestHomeMemberList];
    };
}


- (void)setThingsPopoverOptions {
    //set Popover Contents
    __weak typeof(self) weakSelf = self;
    _popooverOptionArray = [[NSMutableArray alloc] init];

    [_popooverOptionArray addObject:@{@"menuName" : NSLocalizedString(@"새로 고침",nil),
                                      @"iconName": @"img_bg_morepopup_icon_refresh",
                                      @"target": weakSelf,
                                      @"selector": [NSValue valueWithPointer:@selector(requestHomeMemberList)]}];

    if ([JDFacade facade].loginUser.level == 90) {
        
        [_popooverOptionArray addObject:@{@"menuName" : NSLocalizedString(@"멤버 삭제", @"멤버 삭제"),
                                          @"iconName": @"img_bg_morepopup_icon_del",
                                          @"target": weakSelf,
                                          @"selector": [NSValue valueWithPointer:@selector(toggleEditMode)]}];
    } else {
        [_popooverOptionArray addObject:@{@"menuName" : NSLocalizedString(@"멤버 탈퇴", @"멤버 탈퇴"),
                                          @"iconName": @"img_bg_morepopup_icon_del",
                                          @"target": weakSelf,
                                          @"selector": [NSValue valueWithPointer:@selector(leaveHomegroup)]}];
    }
}


- (void)prepareViewDidLoad {
    
    [self updateTitle];
    [self performSelector:@selector(requestHomeMemberList) withObject:nil afterDelay:0.0f];
}


- (void)updateTitle {
    
    NSInteger memberCount = _memberList ? [_memberList filteredArrayUsingPredicateFormat:@"memberTypeCode == %@", @"01"].count : 0;
    NSInteger invitationCount = _memberList ? [_memberList filteredArrayUsingPredicateFormat:@"memberTypeCode == %@", @"02"].count : 0;
    _lblTitle.text = [NSString stringWithFormat:@"참여 %zd / 초대 %zd", memberCount, invitationCount];
    
    if (![JDFacade facade].loginUser.hasHomeHub) {//홈허브 아이디가 없는 경우,
        
        [_mainView bringSubviewToFront:_addHubContainerView];
        _addHubContainerView.hidden = NO;
        _collectionView.hidden = YES;
        _btnOption.hidden = YES;
        
        if (![JDFacade facade].loginUser.homegrpId) {//연결한 적이 없음
            _lblConnectHub.text = @"초대를 받아서\n시작해 보세요";
            _imgvHubAlert.hidden = YES;
            
            _imgvConnectHub.image = [UIImage imageNamed:@"img_1depth_invitation"];
            
            _lblLeaveAccount.hidden = YES;
            _lblSimpleMemberInfo.hidden = YES;
            
        } else {//홈허브가 삭제됨.
            _lblTitle.text = @"     홈허브 삭제됨";
            
            _imgvHubAlert.hidden = NO;
            _lblConnectHub.text = @"홈허브를 다시 연결하려면\n고객센터에 문의해주세요";
            
            _imgvConnectHub.image = [UIImage imageNamed:@"img_things_homehub_img_hubdelete_cscenter"];
            
            if ([JDFacade facade].loginUser.level < 90) {//일반 유저일 경우,
                _imgvConnectHub.image = [UIImage imageNamed:@"img_things_homehub_img_hubdelete_wait"];
                _lblLeaveAccount.hidden = NO;
                _lblSimpleMemberInfo.hidden = NO;
                [_lblLeaveAccount setUnderLine:_lblLeaveAccount.text];
                
                if (!_lblLeaveAccount.touchHandler) {
                    [_lblLeaveAccount addTouchEventHandler:^(id label) {
                        [self leaveHomegroup];
                    }];
                }
            }
        }
    } else {
        
        if (![JDFacade facade].loginUser.isHomehubOnline) {
            _imgvHubAlert.hidden = NO;
            _lblTitle.text = @"     홈허브 오프라인";
            [_lblTitle setColor:kUITextColor01 text:_lblTitle.text];
            
        } else {
            _imgvHubAlert.hidden = YES;
        }
        
        [_mainView bringSubviewToFront:_collectionView];
        _addHubContainerView.hidden = YES;
        _collectionView.hidden = NO;
        _btnOption.hidden = NO;
    }
    
    if ([_lblTitle.text rangeOfString:@"참여"].location != NSNotFound) {
        [_lblTitle setColor:kUITextColor02 text:[NSString stringWithFormat:@"%zd", memberCount]];
        [_lblTitle setColor:kUITextColor03 text:[NSString stringWithFormat:@"초대 %zd", invitationCount]];
    }
}

- (void)updateHomeHubStatusToMembers {
    [self updateTitle];
}


- (IBAction)btnOptionTouched:(id)sender {
    [self toggleOptions:sender];
}

- (IBAction)btnCloseEditModeTouched:(id)sender {
}

- (void)addNewMember {
    UIViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"HomeMemberAddViewController" storyboardName:@"HomeMember"];
    [self presentViewController:vc animated:YES completion:nil];
}

- (void)toggleEditMode {
    _isDeleteMode = !_isDeleteMode;
    
    if (!_isDeleteMode) {
        for (HomeMemberModel *member in _memberList) {
            [[JDFacade facade] setCheckBoxStatus:@(NO) object:member];
        }
        [self updateTitle];
        
    } else {
        _lblTitle.text = @"멤버 삭제";
        _imgvHubAlert.hidden = YES;
    }
    
    [_collectionView reloadData];
    _constraintEditModeRight.constant = _isDeleteMode ? 0 : -_editModeView.width;
    
    [UIView animateWithDuration:kfAnimationDur animations:^{
        [self.view layoutIfNeeded];
    }];
}

- (void)leaveHomegroup {
    
    if (!_masterNickname) {
        
        NSString *path = [NSString stringWithFormat:API_GET_HOMEGROUP_MEMBERS];
        
        [[RequestHandler handler] sendAsyncGetRequestAPIPath:path parameters:nil modelClass:[HomeMemberListModel class] completion:^(id responseObject) {
            if (!responseObject) {//응답결과가 잘못되었거나 없을 경우,
                return;
            }
            
            HomeMemberListModel *fetchedMemberList = (HomeMemberListModel *)responseObject;
            NSArray<HomeMemberModel> *homegrpMemberList = fetchedMemberList.homegrpMemberList;
            
            if (homegrpMemberList && homegrpMemberList.count) {
                HomeMemberModel *master = [homegrpMemberList objectKey:@"gradeCode" eqaulToString:KNEET_MEMBER_MASTER];
                _masterNickname = master && master.nickname ? master.nickname : ksEmptyString;
                
                [self leaveHomegroup];
            }
        } failure:^(id errorObject) {
            JDErrorModel *error = (JDErrorModel *)errorObject;
            [[JDFacade facade] alert:error.errorMessage];
        }];

        return;
    }
    
    NSString *message = [NSString stringWithFormat:@"[%@]님의 홈그룹에서 탈퇴하시겠습니까?", _masterNickname];
    [[JDFacade facade] confirmTitle:@"멤버 탈퇴" message:message completion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
        if (buttonIndex == 0) {//OK
            [self requestLeaveHomegroup];
        }
    }];
}

#pragma mark - Main Logic

- (void)requestHomeMemberList {

    if (![JDFacade facade].loginUser.hasHomeHub) {
        return;
    }
    
    NSString *path = [NSString stringWithFormat:API_GET_HOMEGROUP_MEMBERS];

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

        HomeMemberListModel *fetchedMemberList = (HomeMemberListModel *)responseObject;
        NSArray<HomeMemberModel> *homegrpMemberList = fetchedMemberList.homegrpMemberList;

        if (homegrpMemberList && homegrpMemberList.count) {
            _memberList = homegrpMemberList;

        } else {//조회 내역이 없을 경우,

        }
        
        [self setContents];
        [_collectionView reloadData];
        
        
        //refresh controller
        if (self.refreshController && self.refreshController.refreshState == JYRefreshStateLoading) {
            [self.refreshController stopRefreshWithAnimated:YES completion:nil];
        }

    } failure:^(id errorObject) {
        JDErrorModel *error = (JDErrorModel *)errorObject;
        [[JDFacade facade] alert:error.errorMessage];
    }];
}

- (void)setContents {
    HomeMemberModel *master = [_memberList objectKey:@"gradeCode" eqaulToString:KNEET_MEMBER_MASTER];
    _masterNickname = master && master.nickname ? master.nickname : ksEmptyString;
    
    [self updateTitle];
}

- (void)requestDeleteMembers:(NSString *)memberIds invitations:(NSString *)invitations {
    
    //parameters
    NSDictionary *parameter = @{@"member_ids" : ![memberIds isEmptyString] ? memberIds : ksEmptyString,
                                @"invitation_hist_ids": ![invitations isEmptyString] ? invitations : ksEmptyString};
    
    NSString *path = [NSString stringWithFormat:API_DELETE_HOMEGROUP_MEMBERS];
    
    
    [[RequestHandler handler] sendAsyncRequestAPIPath:path method:ksHTTPRequestDELETE parameters:parameter modelClass:[JDJSONModel class] showLoadingView:YES completion:^(id responseObject) {

        [self toggleEditMode];
        [self requestHomeMemberList];
        [[JDFacade facade] toast:NSLocalizedString(@"멤버를 삭제했습니다", @"멤버를 삭제했습니다")];
        
    } failure:^(id errorObject) {
        JDErrorModel *error = (JDErrorModel *)errorObject;
        [[JDFacade facade] alert:error.errorMessage];
    }];
}


- (void)requestLeaveHomegroup {
    
    //api path
    NSString *path = [NSString stringWithFormat:API_DELETE_HOMEGROUP_MEMBER, [JDFacade facade].loginUser.memberId];

    [[RequestHandler handler] sendAsyncRequestAPIPath:path method:ksHTTPRequestDELETE parameters:nil modelClass:[JDJSONModel class] showLoadingView:YES completion:^(id responseObject) {
        
        [[JDFacade facade] alertTitle:@"멤버 탈퇴" message:@"탈퇴를 완료했습니다" completionHander:^{
            [[JDFacade facade] gotoWishMenu:KNMenuIdDashboard];
        }];
        
    } failure:^(id errorObject) {
        JDErrorModel *error = (JDErrorModel *)errorObject;
        [[JDFacade facade] alert:error.errorMessage];
    }];
}

#pragma mark - UICollectionView Delegate

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    NSInteger auth = [JDFacade facade].loginUser.level == 90 && !_isDeleteMode; //마스터 권한일 경우,
    NSInteger count = _memberList.count % _deviceFlag == 0 ? _memberList.count : _memberList.count + auth; //홀수일 경우, 멤버 초대 버튼을 추가해줌.
    return count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    UICollectionViewCell *rcell = nil;
    
    if (indexPath.row < _memberList.count) {
        HomeMemberCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CollectionCellIdentifier" forIndexPath:indexPath];
        
        HomeMemberModel *member = _memberList[indexPath.row];
        cell.indexPath = indexPath;
        
        [cell.btnProfile sd_setBackgroundImageWithURL:[NSURL URLWithString:member.imageFileName] forState:UIControlStateNormal placeholderImage:nil options:SDWebImageRefreshCached];
        
        cell.lblNickname.text = member.nickname;
        
        if ([member.memberTypeCode isEqualToString:KNEET_MEMBER_TYPE_HOME]) {
            cell.lblNickname.text = [NSString stringWithFormat:@"● %@", cell.lblNickname.text];
            UIColor *pcolor = [member.gradeCode isEqualToString:KNEET_MEMBER_MASTER] ? kUITextColor01 : kUITextColor03;
            [cell.lblNickname setColor:pcolor text:@"●"];
            
            cell.lblStatus.text = member.gradeCodeName;
            [cell.lblStatus setColor:kUITextColor02 text:cell.lblStatus.text];
            
        } else {
            if ([member.invitation isEqualToString:@"01"]) {//초대 대기중
                cell.lblStatus.text = @"초대 대기 중";
            } else if ([member.invitation isEqualToString:@"21"]) {//초대 유효기간 종료
                cell.lblStatus.text = @"초대 무효";
            } else if ([member.invitation isEqualToString:@"22"]) {//답변 오류 제한 초과
                cell.lblStatus.text = @"답변 오류 제한 초과";
            } else if ([member.invitation isEqualToString:@"23"]) {//초대 거절
                cell.lblStatus.text = @"초대 거절";
            }
            
            [cell.lblStatus setColor:kUITextColor03 text:cell.lblStatus.text];
        }
        
        NSInteger mod = indexPath.row % _deviceFlag;
        cell.vline.hidden = mod == (_deviceFlag - 1);

        cell.chkSelect.hidden = !(_isDeleteMode && [member.gradeCode isEqualToString:KNEET_MEMBER_SIMPLE] && _memberList.count > 1);
        cell.chkSelect.value = member;
        cell.chkSelect.checked = [cell.chkSelect getCheckStatusFromValue];
        
        rcell = cell;
    } else {
        HomeMemberAddCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"AddCollectionCellIdentifier" forIndexPath:indexPath];
        
        [cell.btnAdd.label setUnderLine:cell.btnAdd.label.text];
        if (![cell.btnAdd actionsForTarget:self forControlEvent:UIControlEventTouchUpInside]) {
            [cell.btnAdd addTarget:self action:@selector(addNewMember) forControlEvents:UIControlEventTouchUpInside];
        }
        
        NSInteger mod = indexPath.row % _deviceFlag;
        cell.vline.hidden = mod == (_deviceFlag - 1);
        
        rcell = cell;
    }
    
    return rcell;
}


- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView
           viewForSupplementaryElementOfKind:(NSString *)kind
                                 atIndexPath:(NSIndexPath *)indexPath
{
    
    HomeMemberCollectionFooterView *footerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter
                                                                                    withReuseIdentifier:@"FooterIdentifier" forIndexPath:indexPath];
    [footerView.btnAdd.label setUnderLine:footerView.btnAdd.label.text];
    if (![footerView.btnAdd actionsForTarget:self forControlEvent:UIControlEventTouchUpInside]) {
        [footerView.btnAdd addTarget:self action:@selector(addNewMember) forControlEvents:UIControlEventTouchUpInside];
    }
    return footerView;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section {
    if (_memberList.count % _deviceFlag != 0 || [JDFacade facade].loginUser.level < 90 || _isDeleteMode)  {//마스터 권한이 아니거나, 짝수가 아닐 경우
        return CGSizeZero;
    }
    
    return CGSizeMake(IPHONE_WIDTH, 168.0f);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    return CGSizeMake(IPHONE_WIDTH / _deviceFlag, 168.0f);
//    if (IPHONE_WIDTH == 414.0f) {//아이폰 6일 경우,
//    } else if (IPHONE_WIDTH == 375.0f) {//아이폰 6+일경우
//        return CGSizeMake(IPHONE_WIDTH / _deviceFlag, 168.0f);
//    }
//    return CGSizeMake(IPHONE_WIDTH / _deviceFlag, 168.0f);
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
    
    if (indexPath.row < _memberList.count) {
        HomeMemberCollectionCell *cell = (HomeMemberCollectionCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"CollectionCellIdentifier" forIndexPath:indexPath];

        HomeMemberModel *member = _memberList[indexPath.row];
        
        cell.chkSelect.value = member;
        [cell.chkSelect checkBoxClicked];
    }
}

#pragma mark - UI Events

- (IBAction)btnDeleteOnEditModeTouched:(id)sender {
    if (!_isDeleteMode)
        return;
    
    NSMutableString *memberIds = [[NSMutableString alloc] init];
    NSMutableString *invitationHistIds = [[NSMutableString alloc] init];
    
    for (HomeMemberModel *member in _memberList) {
        if ([[[JDFacade facade] getCheckBoxStatus:member] boolValue]) {
            
            if ([member.memberTypeCode isEqualToString:KNEET_MEMBER_TYPE_HOME]) {//홈멤버일 경우,
                NSString *prefix = [memberIds isEmptyString] ? ksEmptyString : @",";
                [memberIds appendFormat:@"%@%@", prefix, member.memberId];
                
            } else if ([member.memberTypeCode isEqualToString:KNEET_MEMBER_TYPE_INV]) {//초대중일 경우,
                NSString *prefix = [invitationHistIds isEmptyString] ? ksEmptyString : @",";
                [invitationHistIds appendFormat:@"%@%@", prefix, member.invitationHistId];
            }
        }
    }
    
    if ([memberIds isEmptyString] && [invitationHistIds isEmptyString]) {
        [[JDFacade facade] alert:NSLocalizedString(@"선택된 멤버가 없습니다", @"선택된 멤버가 없습니다")];
        return;
    }
    
    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 requestDeleteMembers:memberIds invitations:invitationHistIds];
        }
    }];
}

- (IBAction)btnCloseOnEditModeTouched:(id)sender {
    [self toggleEditMode];
}

//- (IBAction)btnCoverIconTouched:(id)sender {
//    
//    if (_selectedCoverIcon) {
//        [_selectedCoverIcon faceOffImage];
//    }
//    
//    CustomButton *btn = (CustomButton *)sender;
//    _selectedCoverIcon = btn;
//    [_selectedCoverIcon faceOffImage];
//}



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


@end
