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

#import "CustomButton.h"
#import "CustomLabel.h"
#import "DatePickerButton.h"

#import "CustomDatePopupView.h"

#import "CustomTextField.h"
#import "ValidateUtil.h"

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

#define kiHeaderCellHeight 100
#define kiAddCellHeight 65
#define kiInputCellHeight 84
#define kiQuizCellHeight 500

/**
 
 - Sub Text Color : kUITextColor04
 - 제목 Text Color : kUITextColor01
 Input Text Color
 - 기본  : kUITextColor01
 - hint : kUITextColor03
 - 달력 아이콘 Text Color : kUITextColor01
 
 **/

@implementation MemberHeaderTableViewCell

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

@end

@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;
    
    _btnDate.date = [NSDate date];

    //    _btnDate.placeHolder = _btnDate.dateString;
    
    _txtQuestion.keyboardType = UIKeyboardTypeDefault;
    _txtQuestion.returnKeyType = UIReturnKeyDone;
    
    _txtQuestion.placeholder = @"퀴즈를 선택하세요.";
    _txtQuestion.customTextFieldSuperview = CustomTextFieldSuperviewIsContentView;
    
    _txtSelfQuiz.keyboardType = UIKeyboardTypeDefault;
    _txtSelfQuiz.returnKeyType = UIReturnKeyDone;
    _txtSelfQuiz.tag = 3333 ;
    _txtSelfQuiz.delegate = self;
    
    
}

-(void)showDirectInputArea:(BOOL)isShow
{
    _viewSelfQuiz.hidden = !isShow;
    
    if(_viewSelfQuiz.isHidden){
        _viewHeight.constant = 0;
    }
    else{
        _viewHeight.constant = 224.0f;
    }
}



@end

@interface HomeMemberAddViewController () <UITableViewDataSource, UITableViewDelegate, CustomTextFieldDelegate, DatePickerButtonDelegate> {
    NSMutableArray<HomeMemberModel> *_inviteList;
    
    CustomTextField *_txtQuestion, *_txtTempEmail, *_txtDirectQuiz;
    DatePickerButton *_btnDate;
    
    DataSelectListModel *_quizList;
    DataSelectModel *_selectedQuiz;
    
    CustomDatePopupView *_popDate;
}
@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 requestInviteQuizList];
}

- (void)initUI {

    
    [self initTableViewAsDefaultStyle:_tableView];
    
    [self.btnCancel setBackgroundImage:[UIImage imageNamed:@"common_button_left_bg"] forState:UIControlStateNormal capInsets:UIEdgeInsetsMake(kfTopInset,kfRightInset,kfBottomInset,kfLeftInset)];
    [self.btnCancel setBackgroundImage:[UIImage imageNamed:@"common_button_left_bg_press"] forState:UIControlStateHighlighted capInsets:UIEdgeInsetsMake(kfTopInset,kfRightInset,kfBottomInset,kfLeftInset)];
    
    [self.btnSend setBackgroundImage:[UIImage imageNamed:@"common_button_right_bg"] forState:UIControlStateNormal capInsets:UIEdgeInsetsMake(kfTopInset,kfRightInset,kfBottomInset,kfLeftInset)];
    [self.btnSend setBackgroundImage:[UIImage imageNamed:@"common_button_right_bg_press"] forState:UIControlStateHighlighted capInsets:UIEdgeInsetsMake(kfTopInset,kfRightInset,kfBottomInset,kfLeftInset)];
    
    //Localization
    [_btnSend setTitle:NSLocalizedString(@"확인", @"확인") forState:UIControlStateNormal];
    [_btnCancel setTitle:NSLocalizedString(@"취소", @"취소") forState:UIControlStateNormal];
    
}


- (void)prepareViewDidLoad {
    [self updateUI];
}

#pragma mark - Main Logic
- (void)requestInviteMembers {
    
    NSMutableArray *invitations = [[NSMutableArray alloc] init];
    for (HomeMemberModel *member in _inviteList) {
        NSMutableDictionary *info = [NSMutableDictionary dictionary];
        info[@"receive_phone"] = member.targetPhone;
        [invitations addObject:info];
    }
    
    QuizModel *quizInfo = (QuizModel *)_selectedQuiz.value;
    NSLog(@"Quiz Info : %@", quizInfo);
    
    NSString *quiz = quizInfo.quiz;
    if (quizInfo.isUserEditQuiz) {
        quiz = [_txtDirectQuiz.text trim];
    }
    
    
    NSString *dateString = [_btnDate.dateString strReplace:@"/" replace:@""];
    dateString = [dateString strReplace:@"-" replace:@""];
    
    //parameters
    NSDictionary *parameter = @{@"member_id": [JDFacade facade].loginUser.memberId,
                                @"quiz": quiz,
                                @"quiz_id": quizInfo.quizId,
                                @"status_code": quizInfo.statusCode,
                                @"answer": dateString,
                                @"invitation_list": invitations};
    // [JDErrorModel class]
    //    NSString *path = [NSString stringWithFormat:API_POST_HOMEGROUP_MEMBER_INVITE];
    NSString *path = [[JDFacade facade] getUrlWithCustAndGroupID:API_POST_HOMEGROUP_MEMBER_INVITE aditional:nil];
    
    [[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 completionHander:^{

            if (EQUALS(error.errorCode, @"201")) {
                
                [_txtTempEmail becomeFirstResponder];
            }
        }];

    }];
    
}

#pragma mark - Quize
- (void)requestInviteQuizList {
    
    if (![JDFacade facade].loginUser.hasHomeHub) {
        return;
    }
    
    
    NSString *path = [NSString stringWithFormat:API_POST_HOMEGROUP_INVITE_QUIZ];
    
    [[RequestHandler handler] sendAsyncGetRequestAPIPath:path parameters:nil modelClass:[QuizListModel class] completion:^(id responseObject) {
        
        QuizListModel *quizList = (QuizListModel *)responseObject;
        
        //NSLog(@"Response : %@", responseObject);
        _quizList = [[DataSelectListModel alloc] init];
        _quizList.title = @"퀴즈를 선택하세요.";
        
        for (QuizModel *info in quizList.quizList) {
            DataSelectModel *data = [[DataSelectModel alloc] init];
            data.title = info.quiz;
            data.value = info;
            [_quizList.list addObject:data];
        }
        
    } failure:^(id errorObject) {
        
        JDErrorModel *error = (JDErrorModel *)errorObject;
        [[JDFacade facade] alert:error.errorMessage];
    }];
    
}



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

- (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 = 0;
    
    if (indexPath.section == 0) {
        height = kiHeaderCellHeight;
    } else if (indexPath.section == 1) {
        height = kiInputCellHeight;
    } else if (indexPath.section == 2) {
        height = kiAddCellHeight;
    } else if (indexPath.section == 3) {
        height = kiQuizCellHeight;
    }
    return height;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = nil;
    
    
    if (indexPath.section == 0) { // title
        MemberHeaderTableViewCell *tcell = [tableView dequeueReusableCellWithIdentifier:@"HeaderCellIdentifier"];
        
        cell = tcell;
        
    } else if (indexPath.section == 1) {// input
        
        MemberInputTableViewCell *tcell = [tableView dequeueReusableCellWithIdentifier:@"InputCellIdentifier"];
        
        _txtTempEmail = !_txtTempEmail ? tcell.txtEmail : _txtTempEmail;
        _txtTempEmail.delegate = self;
        _txtTempEmail.keyboardType = UIKeyboardTypePhonePad;
        
        if (![tcell.btnAdd actionsForTarget:self forControlEvent:UIControlEventTouchUpInside]) {
            [tcell.btnAdd addTarget:self action:@selector(btnAddTouched:) forControlEvents:UIControlEventTouchUpInside];
        }
        
        cell = tcell;
        
    } else if (indexPath.section == 2) {// added
        MemberAddedTableViewCell *tcell = [tableView dequeueReusableCellWithIdentifier:@"AddedCellIdentifier"];
        HomeMemberModel *member = _inviteList[indexPath.row];
        
        tcell.txtEmail.text = member.targetPhone;
        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 == 3) {// Quiz
        
        MemberQuizTableViewCell *tcell = [tableView dequeueReusableCellWithIdentifier:@"QuizCellIdentifier"];
        
        //init controls link
        _txtQuestion = !_txtQuestion ? tcell.txtQuestion : _txtQuestion;
        _txtQuestion.delegate = self;
        _btnDate = !_btnDate ? tcell.btnDate : _btnDate;
        _btnDate.delegate = self;
        
        //        tcell.btnDate.isHidePicker = YES;
        //        [tcell.btnDate addTarget:self action:@selector(showDatePopup) forControlEvents:UIControlEventTouchUpInside];
        
        _txtDirectQuiz = !_txtDirectQuiz ? tcell.txtSelfQuiz : _txtDirectQuiz;
        _txtDirectQuiz.delegate = self;
        
        if (_selectedQuiz != nil) {
            
            QuizModel *info = (QuizModel *)_selectedQuiz.value;
            [tcell showDirectInputArea:[info isUserEditQuiz]];
            _txtQuestion.text = _selectedQuiz.title;
        }
        else {
            
            [tcell showDirectInputArea:NO];
        }
        
        
        //        if (_txtQuestion.customTextFieldSuperview != CustomTextFieldSuperviewIsScrollView) {
        //            _txtQuestion.customTextFieldSuperview = CustomTextFieldSuperviewIsScrollView;
        //        }
        
        cell = tcell;
    }
    
    return cell;
}

- (void)btnAddTouched:(id)sender {
    if (![ValidateUtil validateTextfiled:_txtTempEmail type:ValidateTypeNull title:NSLocalizedString(@"휴대폰 번호", @"휴대폰 번호")]) {
        return;
    }
    
    if (_inviteList.count == 9) {
        
        [[JDFacade facade] alert:@"멤버초대는 1회에 최대 9명까지 초대할 수 있습니다."];
        return;
    }
    
    
    //api - 7.16
    //    NSDictionary *parameter = @{@"target_email" : _txtTempEmail.text};
    
    JDErrorModel *result = [[RequestHandler handler] sendSyncGetRequestAPIPath:[self getInviteNumberValidateUrl:[_txtTempEmail.text trim]] parameters:nil modelClass:[JDErrorModel class] showLoadingView:YES];
    
    if (!result) {
    
        HomeMemberModel *member = [[HomeMemberModel alloc] init];
        member.targetPhone = _txtTempEmail.text;
        member.gradeCode = KNEET_MEMBER_SIMPLE;
        
        [_inviteList addObject:member];
        _txtTempEmail.text = ksEmptyString;
        
        //        [_tableView reloadData];
        [self updateUI];
        
    } else {

        [[JDFacade facade] alert:result.errorMessage];
    }
}

-(NSString *)getInviteNumberValidateUrl:(NSString *)number
{
    //    NSMutableArray *arr = [NSMutableArray array];
    //    arr[0] = [JDFacade facade].loginUser.memberId;
    //    arr[1] = number;
    NSArray *arr = @[
                     [JDFacade facade].loginUser.memberId,
                     number
                     ];
    
    return [[JDFacade facade] getUrlWithCustAndGroupID:API_GET_HOMEGROUP_MEMBER_VALIDATE arguments:arr];
}

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


- (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];
    [self updateUI];
}

- (BOOL)isValidRequestInfo {
    BOOL result = YES;
    QuizModel *quizInfo = (_selectedQuiz != nil) ? (QuizModel *)_selectedQuiz.value : nil;
    
    if (_inviteList.count <= 0) {
        result = NO;
    }
    if (result && quizInfo == nil)
    {
        result = NO;
    }
    if (result && quizInfo.isUserEditQuiz)
    {
        if ([[_txtDirectQuiz.text trim] isEmptyString] || _txtDirectQuiz.text.length < 3 || _txtDirectQuiz.text.length > 20) {
            result = NO;
        }
    }
    if (result && ([_btnDate.dateString isEmptyString] || [[_btnDate titleForState:UIControlStateNormal] isEqualToString:_btnDate.placeHolder]))
    {
        result = NO;
    }
    
    return result;
}


- (void)updateUI {
    _btnSend.enabled = [self isValidRequestInfo];
    [_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 || [_txtQuestion.text isEqualToString:ksEmptyString])) {
    //        [[JDFacade facade] alert:@"멤버 인증 퀴즈를 선택해 주세요."];
    //        return;
    //    }
    //
    //    if (_txtDirectQuiz.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];
}


-(void)showQuizList{
    [[JDFacade facade] selectDatas:self listInfo:_quizList completion:^(DataSelectModel *seleced) {
        _selectedQuiz = seleced;
        _txtQuestion.text = _selectedQuiz.title;
        //        [_tableView reloadData];
        [self updateUI];
    }];
}


-(void)showDatePopup {
    //    if (_popDate == nil) {
    //        _popDate = [[CustomDatePopupView alloc] initWithTitle:@"정답 날짜 입력"];
    //    }
    //
    //    [_popDate showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
    //        if (buttonIndex == 0) {//OK
    //            NSLog(@"Input Date : %@.%@.%@", _popDate.txtYear.text, _popDate.txtMonth.text, _popDate.txtDay.text);
    //        }
    //    }];
}



#pragma mark datepicker button delegate
- (void)didDoneClicked:(id)sender {
 
    _btnSend.enabled = [self isValidRequestInfo];
}


#pragma mark - UITextField Delegate
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    if ([textField isEqual:_txtQuestion]) {
        [self showQuizList];
        return NO;
    }
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    NSLog(@"text textfiled delegate return tag : %ld", textField.tag) ;
    
    if ([textField isEqual:_txtTempEmail]) {
        [self btnAddTouched:nil];
    }
    else if (textField.tag == 3333) {
        [textField resignFirstResponder];
    }
    return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    
    _btnSend.enabled = [self isValidRequestInfo];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    NSString *text = [textField.text stringByReplacingCharactersInRange:range withString:string];
    
    if (text.length > 11) {
        
        return NO;
    }
    
    return YES;
}


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




@end
