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

#import "HomeMemberViewController.h"
#import "CustomButton.h"
#import "LoginModel.h"
#import "RequestHandler.h"
#import "CustomLabel.h"
#import "UIButton+WebCache.h"
#import "HomeMemberDetailViewController.h"

#define kfMemberTableViewCellHeight 100.0f

@protocol MembersHeaderTableViewCellDelegate <NSObject>
@optional
- (void)didMemberHeaderTableViewCellBtnHeaderTouched:(id)sender;

@end

@interface MemberHeaderTableViewCell () {
}

@property (assign, nonatomic) id <MembersHeaderTableViewCellDelegate> delegate;
@end

@implementation MemberHeaderTableViewCell

- (IBAction)btnHeaderTouched:(id)sender {
    [_btnHeader faceOffImage];
    _group[@"unfold"] = @(![_group[@"unfold"] boolValue]);

    if ([self.delegate respondsToSelector:@selector(didMemberHeaderTableViewCellBtnHeaderTouched:)]) {
        [self.delegate didMemberHeaderTableViewCellBtnHeaderTouched:self];
    }
}

@end

@implementation MemberTableViewCell

- (void)awakeFromNib {
    self.backgroundColor = [UIColor clearColor];
    self.selectionStyle = UITableViewCellSelectionStyleNone;
    self.opaque = NO;
}

@end

@implementation MemberAddTableViewCell

- (void)awakeFromNib {
    self.backgroundColor = [UIColor clearColor];
    self.selectionStyle = UITableViewCellSelectionStyleNone;
    
    _lblAddTitle.text = NSLocalizedString(@"주변 사람들을 초대하세요!", @"주변 사람들을 초대하세요!");
    _lblAddDesc.text = NSLocalizedString(@"멤버가 되면 내장치를 같이 쓸 수 있어요\n편리한 자동 규칙도 함께 만들어보세요", @"멤버가 되면 내장치를 같이 쓸 수 있어요\n편리한 자동 규칙도 함께 만들어보세요");
}

- (void)btnAddTouched:(id)sender {
    UIViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"HomeMemberAddViewController" storyboardName:@"HomeMember"];
    [[JDFacade facade].currentViewController.navigationController pushViewController:vc animated:YES];
}

@end

@interface HomeMemberViewController () <UITableViewDataSource, UITableViewDelegate, MembersHeaderTableViewCellDelegate> {
    NSMutableArray *_groups;
    UIImage *_bgCellImage1, *_bgCellImage2;
    NSMutableArray *_arrayForHeader;
}
@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 {
    

    
    [self generateOptionButton];

    //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 = [CommonUtil resizableImageWithCapInsets:insets resizingMode:UIImageResizingModeStretch img:[UIImage imageNamed:@"tp_01_img_list_bg_02"]];
    _bgCellImage2 = [CommonUtil resizableImageWithCapInsets:insets resizingMode:UIImageResizingModeStretch img:[UIImage imageNamed:@"tp_01_img_list_bg_01"]];


    [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(@"새 멤버 추가",nil),
                                          @"iconName": @"tp_01_img_bg_morepopup_icon_group_deviceadd",
                                          @"target": weakSelf,
                                          @"selector": [NSValue valueWithPointer:@selector(addNewMember)]}];        
    }
}


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

- (void)refreshHomeMemberList {
    if (_groups && _groups.count) {
        [_groups removeAllObjects];
        _groups = nil;
    }

    [self requestHomeMemberList];
}

- (void)addNewMember {
    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) {
            _groups = [[NSMutableArray alloc] init];
            _arrayForHeader = [[NSMutableArray alloc] init]; //헤더 저장용으로 사용

            NSIndexSet *isComplete = [homegrpMemberList indexesOfObjectsPassingTest:^BOOL(HomeMemberModel *lmember, NSUInteger idx, BOOL *stop) {//초대완료
                return [lmember.invitation isEqualToString:@"11"];
            }];
            NSIndexSet *isProgress = [homegrpMemberList indexesOfObjectsPassingTest:^BOOL(HomeMemberModel *lmember, NSUInteger idx, BOOL *stop) {//초대 중
                return [lmember.invitation isEqualToString:@"01"];
            }];
            NSIndexSet *isReject = [homegrpMemberList indexesOfObjectsPassingTest:^BOOL(HomeMemberModel *lmember, NSUInteger idx, BOOL *stop) {//초대 거절
                return [lmember.invitation isEqualToString:@"23"];
            }];

            [_groups addObject:[NSMutableDictionary dictionaryWithDictionary:@{@"list":[homegrpMemberList objectsAtIndexes:isComplete]}]];
            [_groups addObject:[NSMutableDictionary dictionaryWithDictionary:@{@"list":[homegrpMemberList objectsAtIndexes:isProgress]}]];
            [_groups addObject:[NSMutableDictionary dictionaryWithDictionary:@{@"list":[homegrpMemberList objectsAtIndexes:isReject]}]];

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

        }

        [_tableView reloadData];

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

}

#pragma mark - UITableView DataSource & Delegate

- (NSString *)titleForSection:(NSInteger)section {
    NSString *title = nil;
    switch (section) {
        case 0:
            title = NSLocalizedString(@"이용 중인 멤버", @"이용 중인 멤버");
            break;
        case 1:
            title = NSLocalizedString(@"초대 중인 멤버", @"초대 중인 멤버");
            break;
        case 2:
            title = NSLocalizedString(@"거절한 멤버", @"거절한 멤버");
            break;
    }
    return title;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _groups.count + ([JDFacade facade].loginHomeGroup.level == 90 ? 1 : 0);
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section == _groups.count) {
        return nil;
    }

    if (!_groups.count) {
        return nil;
    }

    NSMutableDictionary *group = _groups[section];
    UIView *view = _arrayForHeader.count > section ? _arrayForHeader[section] : nil;
    if (!view) {
        MemberHeaderTableViewCell *hcell = (MemberHeaderTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"HeaderCellIdentifier"];

        view = [[UIView alloc] initWithFrame:hcell.contentView.frame];
        [view addSubview:hcell];

        //        NSLog(@"hcell=%p", &hcell);
        hcell.delegate = self;
        hcell.section = section;
        hcell.group = group;


        NSString *headerTitle = [NSString stringWithFormat:@"%@", [self titleForSection:section]];
        [hcell.btnHeader setTitle:headerTitle forState:UIControlStateNormal];

        if (_arrayForHeader.count == section) {
            [_arrayForHeader insertObject:view atIndex:section];
        }
    } else {
        MemberHeaderTableViewCell *hcell = (MemberHeaderTableViewCell *)view.subviews[0];
        NSString *headerTitle = [NSString stringWithFormat:@"%@", [self titleForSection:section]];
        [hcell.btnHeader setTitle:headerTitle forState:UIControlStateNormal];
    }

    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {

    if (section == _groups.count) {
        return 0.01f;
    }
    return 40.0f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01f;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    if (_groups.count == section) {//추가 셀,
        return 1;
    }

    NSMutableDictionary *group = _groups[section];
    NSArray<HomeMemberModel> *memberList = group[@"list"];
    if ([group[@"unfold"] boolValue]) {
        return 0;
    }

    return memberList.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat height = kfMemberTableViewCellHeight;

    if (indexPath.section == _groups.count) {
        height = _groups.count ? 210.0f : IPHONE_HEIGHT - kfNavigationBarHeight;
        _tableView.scrollEnabled = _groups.count;
    }

    return height;
}

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

    UITableViewCell *cell = nil;

//    NSInteger section = indexPath.section;
    if (indexPath.section < _groups.count) {
        NSMutableDictionary *group = _groups[indexPath.section];
        NSArray<HomeMemberModel> *memberList = group[@"list"];
        HomeMemberModel *member = memberList[indexPath.row];

        MemberTableViewCell *tcell = [tableView dequeueReusableCellWithIdentifier:@"CellIdentifier"];

        if (tcell == nil) {
            tcell = [[MemberTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CellIdentifier"];
        }

        tcell.lblTitle.text = member.nickname;
        tcell.lblLevel.text = [NSString stringWithFormat:@"[%@]", member.gradeCodeName];
        [tcell.btnMemberIcon sd_setImageWithURL:[NSURL URLWithString:member.imageFileName] forState:UIControlStateNormal];

        cell = tcell;

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

    } else {
        MemberAddTableViewCell *acell = [tableView dequeueReusableCellWithIdentifier:@"AddCellIdentifier"];

        if (acell == nil) {
            acell = [[MemberAddTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"AddCellIdentifier"];
        }
        cell = acell;
    }

    return cell;
}

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

    if (indexPath.section == _groups.count) {//add new
        [self addNewMember];
        return;
    }

    if ([JDFacade facade].loginHomeGroup.level == 90) {//마스터일 경우에만, 상세로 이동
        
        NSMutableDictionary *group = _groups[indexPath.section];
        NSArray<HomeMemberModel> *memberList = group[@"list"];
        HomeMemberModel *member = memberList[indexPath.row];
        
        HomeMemberDetailViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"HomeMemberDetailViewController" storyboardName:@"HomeMember"];
        vc.member = member;
        [self.navigationController pushViewController:vc 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 - MemberHeaderTableViewCellDelegate
- (void)didMemberHeaderTableViewCellBtnHeaderTouched:(id)sender {

    MemberHeaderTableViewCell *hcell = (MemberHeaderTableViewCell *)sender;
    BOOL isExpanded = ![hcell.group[@"unfold"] boolValue];

    [_tableView enumarateTableViewCellsSection:hcell.section UsingBlock:^(UITableViewCell *cell) {
        MemberHeaderTableViewCell *tmpCell = (MemberHeaderTableViewCell *)cell;
        tmpCell.contentView.hidden = isExpanded;
    }];

    [_tableView reloadData];
}

#pragma mark - UI Events



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

@end
