//
//  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 "UIImageView+WebCache.h"

#import "HomeMemberDetailViewController.h"
#import "HomeMemberViewController.h"
#import "CustomImageView.h"

#define kfMemberTableViewCellHeight 100.0f

@interface HomeMemberCollectionCell () {
    
}

@property (weak, nonatomic) NSIndexPath *indexPath;

@end


@implementation HomeMemberCollectionCell

@end

@implementation HomeMemberCollectionFooterView

- (void)awakeFromNib {

}

@end


@interface HomeMemberViewController () <UICollectionViewDelegate, UICollectionViewDataSource> {
    NSMutableArray *_groups;
    NSArray<HomeMemberModel> *_memberList;
}
@end


#pragma mark - Class Definition

@implementation HomeMemberViewController


- (void)viewDidLoad {
    [super viewDidLoad];

    [self initUI];
    [self prepareViewDidLoad];
}

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

    self.title = NSLocalizedString(@"홈 멤버", @"홈 멤버");
}

- (void)initUI {

    //set tableview option
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.scrollEnabled = NO;
    _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].loginHomeGroup.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(deleteMember)]}];
    }
}


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

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

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

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

- (void)deleteMember {
    UIViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"HomeMemberAddViewController" storyboardName:@"HomeMember"];
    [self.navigationController pushViewController:vc animated:YES];
}

#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];
    }];
}

#pragma mark - UICollectionView Delegate

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    NSInteger count = _memberList.count % 2 == 0 ? _memberList.count : _memberList.count + 1; //홀수일 경우, 멤버 초대 버튼을 추가해줌.
    return _memberList.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *kCellID = @"CollectionCellIdentifier";
    HomeMemberCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kCellID forIndexPath:indexPath];
    
    HomeMemberModel *member = nil;
    if (indexPath.row < _memberList.count) {
        member = _memberList[indexPath.row];
    }
    
    cell.indexPath = indexPath;
//    cell.btnMemberIcon.value = memberIcon;
//    cell.btnCover.value = cell.btnMemberIcon;
    
    [cell.imgvMemberIcon sd_setImageWithURL:[NSURL URLWithString:member.imageFileName] placeholderImage:nil options:SDWebImageRefreshCached];
    [cell.imgvMemberIcon setContentMode:UIViewContentModeScaleAspectFit];

    cell.lblNickname.text = member.nickname;
    cell.lblStatus.text = member.gradeCodeName;
    
    return cell;
}


/*
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView
           viewForSupplementaryElementOfKind:(NSString *)kind
                                 atIndexPath:(NSIndexPath *)indexPath
{
    HomeMemberCollectionFooterView *footerView = nil;
    if (indexPath.row == _memberList.count) {
//    MemberIconeHeaderView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:
//                                         UICollectionElementKindSectionHeader withReuseIdentifier:@"HeaderView" forIndexPath:indexPath];
//    return headerView;
    }
}
*/

- (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);
}

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



#pragma mark - UI Events



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

@end
