//
//  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 "CustomImageView.h"
#import "CustomCheckBox.h"
#import "UIImageView+WebCache.h"

#import "HomeMemberViewController.h"
#import "CustomAlertView.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;
}
@end


#pragma mark - Class Definition

@implementation HomeMemberViewController


- (void)viewDidLoad {
    [super viewDidLoad];

    [self initUI];
}

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

    [self prepareViewDidLoad];
}

- (void)initUI {

    //set tableview option
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.backgroundColor = kUIBgColor01;

    [self setThingsPopoverOptions];
}

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

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

    if ([JDFacade facade].loginUser.level == 90) {
        [_popooverOptionArray addObject:@{@"menuName" : NSLocalizedString(@"초대", @"초대"),
                                          @"iconName": @"tp_01_img_bg_morepopup_icon_group_deviceadd",
                                          @"target": weakSelf,
                                          @"selector": [NSValue valueWithPointer:@selector(addNewMember)]}];
        
        [_popooverOptionArray addObject:@{@"menuName" : NSLocalizedString(@"삭제", @"삭제"),
                                          @"iconName": @"tp_01_img_bg_morepopup_icon_group_deviceadd",
                                          @"target": weakSelf,
                                          @"selector": [NSValue valueWithPointer:@selector(toggleEditMode)]}];
    }
}


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


- (void)updateHomeHubStatusToMembers {
    
}

- (void)refreshHomeMemberList {
    [self requestHomeMemberList];
}

- (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];
        }
    }
    
    [_collectionView reloadData];
    _constraintEditModeRight.constant = _isDeleteMode ? 0 : -_editModeView.width;
    
    [UIView animateWithDuration:kfAnimationDur animations:^{
        [self.view layoutIfNeeded];
    }];
}

#pragma mark - Main Logic

- (void)requestHomeMemberList {

    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 {//조회 내역이 없을 경우,

        }

        [_collectionView reloadData];

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

- (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 requestHomeMemberList];
        [[JDFacade facade] toast:NSLocalizedString(@"멤버를 삭제했습니다", @"멤버를 삭제했습니다")];
        
    } 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 % 2 == 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.imgvMemberIcon sd_setImageWithURL:[NSURL URLWithString:member.imageFileName] placeholderImage:nil options:SDWebImageRefreshCached completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            [cell layoutIfNeeded];
        }];
        
        cell.lblNickname.text = member.nickname;
        cell.lblStatus.text = member.gradeCodeName;
        
        cell.chkSelect.hidden = !_isDeleteMode;
        cell.chkSelect.value = member;
        cell.chkSelect.checked = [cell.chkSelect getCheckStatusFromValue];
        
        rcell = cell;
    } else {
        HomeMemberAddCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"AddCollectionCellIdentifier" forIndexPath:indexPath];
        
        if (![cell.btnAdd actionsForTarget:self forControlEvent:UIControlEventTouchUpInside]) {
            [cell.btnAdd addTarget:self action:@selector(addNewMember) forControlEvents:UIControlEventTouchUpInside];
        }
        rcell = cell;
    }
    
    return rcell;
}


- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView
           viewForSupplementaryElementOfKind:(NSString *)kind
                                 atIndexPath:(NSIndexPath *)indexPath
{
    HomeMemberCollectionFooterView *footerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter
                                                                                    withReuseIdentifier:@"FooterIdentifier" forIndexPath:indexPath];
    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 {

    //FIXME : 권한 추가
//    if (_memberList.count % 2 == 1 || [JDFacade facade].loginUser.level < 90 || _isDeleteMode)  {//마스터 권한이 아니거나, 짝수가 아닐 경우
    if (_memberList.count % 2 == 1 || _isDeleteMode)  {//마스터 권한이 아니거나, 짝수가 아닐 경우
        return CGSizeZero;
    }
    
    return CGSizeMake(IPHONE_WIDTH, 160.0f);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (IPHONE_WIDTH == 414.0f) {//아이폰 6일 경우,
        return CGSizeMake(212.0f, 160.0f);
    } else if (IPHONE_WIDTH == 375.0f) {//아이폰 6+일경우
        return CGSizeMake(187.5, 160.0f);
    }
    return CGSizeMake(160.0f, 160.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
