//
//  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 "CustomTextField.h"
#import "ValidateUtil.h"

#import "HomeMemberAddViewController.h"
#import "HomeMemberViewController.h"
#import "CustomTableView.h"

@implementation MemberInputTableViewCell

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

@end

@implementation MemberAddedTableViewCell

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

@end

@implementation MemberQuizTableViewCell

- (void)awakeFromNib {
    self.backgroundColor = [UIColor clearColor];
    self.selectionStyle = UITableViewCellSelectionStyleNone;
    
    _lblQuizInfo.text = NSLocalizedString(@"우리만 아는 특별한 날을 물어보세요\n진짜 멤버라면 바로 맞출 수 있을거예요", @"우리만 아는 특별한 날을 물어보세요\n진짜 멤버라면 바로 맞출 수 있을거예요");
    
    _btnDate.date = [NSDate date];
//    _btnDate.placeHolder = _btnDate.dateString;
    
    _txtQuestion.keyboardType = UIKeyboardTypeDefault;
    _txtQuestion.returnKeyType = UIReturnKeyDone;
    
    _txtQuestion.placeholder = @"예) 아빠 생일은?";
    _txtQuestion.customTextFieldSuperview = CustomTextFieldSuperviewIsContentView;
}

@end

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

    CustomTextField *_txtQuestion, *_txtTempEmail;
    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];
}

- (void)initUI {
    
    [self initTableViewAsDefaultStyle:_tableView];
    
    //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};

    NSString *path = [NSString stringWithFormat:API_POST_HOMEGROUP_MEMBER_INVITE];
    
    [[RequestHandler handler] sendAsyncPostRequestAPIPath:path parameters:parameter modelClass:[JDJSONModel class] completion:^(id responseObject) {
        
        [self dismissViewControllerAnimated:YES completion:^{
            [[JDFacade facade] toast:NSLocalizedString(@"초대장을 보냈습니다", @"초대장을 보냈습니다")];
        }];
        
        
    } 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 == 0) {
        count = _inviteList.count;
    }

    return count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat height = 0;
    if (indexPath.section == 0) {
        height = 68;
    } else if (indexPath.section == 1) {
        height = 92;
    } else if (indexPath.section == 2) {
        height = 256;
    }
    return height;
}

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

    UITableViewCell *cell = nil;

    if (indexPath.section == 0) {//added
        MemberAddedTableViewCell *tcell = [tableView dequeueReusableCellWithIdentifier:@"AddedCellIdentifier"];
        HomeMemberModel *member = _inviteList[indexPath.row];
        
        tcell.txtEmail.text = member.targetEmail;
        tcell.btnRemove.value = member;
        
        if (![tcell.btnRemove actionsForTarget:self forControlEvent:UIControlEventTouchUpInside]) {
            [tcell.btnRemove addTarget:self action:@selector(btnRemoveTouched:) forControlEvents:UIControlEventTouchUpInside];
        }
        
        cell = tcell;
        
    } else if (indexPath.section == 1) {//input
        MemberInputTableViewCell *tcell = [tableView dequeueReusableCellWithIdentifier:@"InputCellIdentifier"];
        
        _txtTempEmail = !_txtTempEmail ? tcell.txtEmail : _txtTempEmail;
        _txtTempEmail.delegate = self;
        
        if (![tcell.btnAdd actionsForTarget:self forControlEvent:UIControlEventTouchUpInside]) {
            [tcell.btnAdd addTarget:self action:@selector(btnAddTouched:) forControlEvents:UIControlEventTouchUpInside];
        }
        
        cell = tcell;
    } else if (indexPath.section == 2) {//invite list
        
        MemberQuizTableViewCell *tcell = [tableView dequeueReusableCellWithIdentifier:@"QuizCellIdentifier"];

        //init controls link
        _txtQuestion = !_txtQuestion ? tcell.txtQuestion : _txtQuestion;
        _btnDate = !_btnDate ? tcell.btnDate : _btnDate;
        
//        if (_txtQuestion.customTextFieldSuperview != CustomTextFieldSuperviewIsScrollView) {
//            _txtQuestion.customTextFieldSuperview = CustomTextFieldSuperviewIsScrollView;
//        }
        
        cell = tcell;
    }

    return cell;
}

- (void)btnAddTouched:(id)sender {
    if (![ValidateUtil validateTextfiled:_txtTempEmail type:ValidateTypeEmail title:NSLocalizedString(@"이메일", @"이메일")]) {
        return;
    }
    
    HomeMemberModel *member = [[HomeMemberModel alloc] init];
    member.targetEmail = _txtTempEmail.text;
    member.gradeCode = KNEET_MEMBER_SIMPLE;
    
    //api - 12.5
    NSDictionary *parameter = @{@"target_email" : _txtTempEmail.text};
    
    JDErrorModel *result = [[RequestHandler handler] sendSyncPostRequestAPIPath:API_POST_HOMEGROUP_MEMBER_VALIDATE parameters:parameter modelClass:[JDErrorModel class] showLoadingView:YES];
    if (!result) {
        [_inviteList addObject:member];
        _txtTempEmail.text = ksEmptyString;
        
        [_tableView reloadData];
    } else {
        [[JDFacade facade] alert:result.errorMessage];
    }
}

- (void)btnRemoveTouched:(id)sender {
    CustomButton *btnRemove = (CustomButton *)sender;
    
    HomeMemberModel *member = btnRemove.value;
    [_inviteList removeObject:member];
    
    [_tableView reloadData];
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [super tableView:tableView didSelectRowAtIndexPath:indexPath];
}

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


- (IBAction)btnSendTouched:(id)sender {
    //1.validate

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

    if (![ValidateUtil validateTextfiled:_txtQuestion type:ValidateTypeNull title:NSLocalizedString(@"퀴즈", @"퀴즈")]) {
        return;
    }
    
    if (_txtQuestion.text.length > 60) {
        [[JDFacade facade] alert:@"퀴즈는 최대 60자까지 입력할 수 있습니다"];
        return;
    }
    
    if ([_btnDate.dateString isEmptyString] || [[_btnDate titleForState:UIControlStateNormal] isEqualToString:_btnDate.placeHolder]) {
        [[JDFacade facade] alert:@"정답 날짜를 입력하세요"];
        return;
    }

    [self requestInviteMembers];
}

- (IBAction)btnCancelTouched:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}


#pragma mark - UITextField Delegate 

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if ([textField isEqual:_txtTempEmail]) {
        [self btnAddTouched:nil];
    }
    return YES;
}

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




@end
