//
//  HomeMemberAddViewController.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 "DatePickerButton.h"

#import "HomeMemberAddViewController.h"
#import "CustomTextField.h"
#import "MemberAddPopupView.h"
#import "ValidateUtil.h"
#import "HomeMemberViewController.h"

@implementation MemberInputTableViewCell

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

    _lblInputTitle.text = NSLocalizedString(@"우리만 아는 특별한 날을 물어보세요\n진짜 멤버라면 바로 맞출 수 있을거예요", @"우리만 아는 특별한 날을 물어보세요\n진짜 멤버라면 바로 맞출 수 있을거예요");
    
    _btnDate.date = [NSDate date];
    _btnDate.placeHolder = _btnDate.dateString;

    _txtQuestion.keyboardType = UIKeyboardTypeDefault;
    _txtQuestion.returnKeyType = UIReturnKeyDone;
    
    _txtQuestion.placeholder = NSLocalizedString(@"ex) 우리집 강아지 뽀삐의 생일은?", @"ex) 우리집 강아지 뽀삐의 생일은?");
}

@end

@implementation MemberInviteTableViewCell

- (void)awakeFromNib {
    self.backgroundColor = [UIColor clearColor];
    self.selectionStyle = UITableViewCellSelectionStyleNone;
    
    _lblInviteDesc.text = NSLocalizedString(@"초대할 이메일을 입력하세요", @"초대할 이메일을 입력하세요");
}

@end

@implementation MemberEmailTableViewCell

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

@end

@interface HomeMemberAddViewController () <UITableViewDataSource, UITableViewDelegate> {
    NSMutableArray<HomeMemberModel> *_inviteList;
    UIImage *_bgCellImage1, *_bgCellImage2;

    CustomTextField2 *_txtQuestion;
    DatePickerButton *_btnDate;
}
@end


#pragma mark - Class Definition

@implementation HomeMemberAddViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    _inviteList = (NSMutableArray<HomeMemberModel> *)[[NSMutableArray alloc] init];

    [self initUI];
    [self prepareViewDidLoad];
}



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

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

- (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 = [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"]];
    
    //Localization
    [_btnSend setTitle:NSLocalizedString(@"초대보내기", @"초대보내기") forState:UIControlStateNormal];
    [_btnCancel setTitle:NSLocalizedString(@"취소", @"취소") forState:UIControlStateNormal];
}


- (void)prepareViewDidLoad {

}

#pragma mark - Main Logic

- (void)requestInviteMembers {

    NSMutableArray *invitations = [[NSMutableArray alloc] init];
    for (HomeMemberModel *member in _inviteList) {
        [invitations addObject:[member toDictionary]];
    }

    //parameters
    NSDictionary *parameter = @{@"authorization_question": _txtQuestion.text,
                                @"authorization_reply": _btnDate.dateString,
                                @"invitation_list": invitations}; //TODO : dictionary;

    NSString *path = [NSString stringWithFormat:API_POST_HOMEGROUP_MEMBER_INVITE];
    
    [[RequestHandler handler] sendAsyncPostRequestAPIPath:path parameters:parameter modelClass:[JDJSONModel class] completion:^(id responseObject) {
        
        [[JDFacade facade] toast:NSLocalizedString(@"초대장을 보냈습니다", @"초대장을 보냈습니다")];
        HomeMemberViewController *vc = [[JDFacade facade] viewControllerOnNaviationController:[HomeMemberViewController class]];
        if (vc) {
            [vc refreshHomeMemberList];
        }
        
        [self.navigationController popViewControllerAnimated:YES];
        
        
    } failure:^(id errorObject) {
        JDErrorModel *error = (JDErrorModel *)errorObject;
        [[JDFacade facade] alert:error.errorMessage];
    }];

}

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

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

    if (section == 2) {
        count = _inviteList.count;
    }

    return count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat height = 80;
    if (indexPath.section == 0) {
        height = 200;
    }
    return height;
}

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

    UITableViewCell *cell = nil;

    if (indexPath.section == 0) {//input
        MemberInputTableViewCell *tcell = [tableView dequeueReusableCellWithIdentifier:@"InputCellIdentifier"];

        _txtQuestion = !_txtQuestion ? tcell.txtQuestion : _txtQuestion;
        _btnDate = !_btnDate ? tcell.btnDate : _btnDate;

        cell = tcell;
    } else if (indexPath.section == 1) {//add
        MemberInviteTableViewCell *tcell = [tableView dequeueReusableCellWithIdentifier:@"AddCellIdentifier"];

        [tcell.btnInvite addTarget:self action:@selector(btnInviteTouched:) forControlEvents:UIControlEventTouchUpInside];

        cell = tcell;
    } else if (indexPath.section == 2) {//invite list
        MemberEmailTableViewCell *tcell = [tableView dequeueReusableCellWithIdentifier:@"CellIdentifier"];

        HomeMemberModel *member = _inviteList[indexPath.row];
        tcell.lblEmail.text = member.targetEmail;
        tcell.lblLevel.text = [member.gradeCode isEqualToString:KNEET_MEMBER_POWER] ? NSLocalizedString(@"파워멤버", @"파워멤버") : NSLocalizedString(@"심플멤버", @"심플멤버");
        tcell.btnDelete.value = member;

        [tcell.btnDelete addTarget:self action:@selector(btnDeleteTouched:) 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];

    if (indexPath.section == 0)
        return;

    if (indexPath.section == 1) {
        [self btnInviteTouched:nil];
        return;
    }

}


- (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)btnDeleteTouched:(id)sender {
    CustomButton *btn = (CustomButton *)sender;
    HomeMemberModel *member = btn.value;

    [_inviteList enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        [_inviteList removeObject:member];
    }];

    [_tableView reloadData];
}

- (void)btnInviteTouched:(id)sender {
    //pop
    if (_inviteList.count == 10) {
        [[JDFacade facade] alert:NSLocalizedString(@"한 번에 10명까지만\n초대할 수 있습니다", @"한 번에 10명까지만\n초대할 수 있습니다")];
        return;
    }
    MemberAddPopupView *popup = [[MemberAddPopupView alloc] initFromNib];
    popup.inviteList = _inviteList;
    [popup showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
        if (buttonIndex == 0) {//OK
            [_inviteList addObject:[popup newMember]];
            [_tableView reloadData];
        }
    }];
}


- (IBAction)btnSendTouched:(id)sender {
    //1.validate
    if (_inviteList.count <= 0) {
        [[JDFacade facade] alert:NSLocalizedString(@"초대할 이메일을 입력하세요", @"초대할 이메일을 입력하세요")];
        return;
    }

    if (![ValidateUtil validateTextfiled:_txtQuestion type:ValidateTypeNull title:NSLocalizedString(@"퀴즈", @"퀴즈")]) {
        return;
    }

    [self requestInviteMembers];
}

- (IBAction)btnCancelTouched:(id)sender {

}


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


@end
