//
//  PwAnswerViewController.m
//  OneCable
//
//  Created by nComz on 2017. 3. 31..
//  Copyright © 2017년 ntels. All rights reserved.
//

#import "PwAnswerViewController.h"

#import "CustomLabel.h"
#import "CustomButton.h"
#import "CustomTextField.h"
#import "CustomDatePopupView.h"
#import "RequestHandler.h"
#import "PwFindCompleteViewController.h"

@interface PwAnswerViewController () <CustomTextFieldDelegate>{
    
    UIBarButtonItem *_btnKeyboardNext, *_btnKeyboardClose;  // 키보드 출력시 다음,닫기 버튼추가
    UIToolbar *_toolBar;                                    // 툴바 설정
    NSMutableArray *_barItems;                              // 툴바에 추가할 아이템
    UIBarButtonItem *_btnFlexibleSpace;                     // 여백 설정
    
    DataSelectListModel *_quizList; // 퀴즈 목록 모델
    DataSelectModel *_selectedQuiz; // 선택 한 퀴즈
    CustomDatePopupView *_popDate;  // 정답 입력 팝업
}

@end

@implementation PwAnswerViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self initUI];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

}

// 퀴즈 목록을 가져옴
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self requestQuizList];
    
}


- (void)initUI {
    
    [self.navigationController.navigationBar setHidden:YES];
    self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    
    _txtYear.customTextFieldSuperview = CustomTextFieldSuperviewIsScrollView;
    _txtMonth.customTextFieldSuperview = CustomTextFieldSuperviewIsScrollView;
    _txtDay.customTextFieldSuperview = CustomTextFieldSuperviewIsScrollView;
    
    [_lblStep setColor:kUITextColor03 text:[NSString stringWithFormat:@"%@", @"/ 3"]];
//    
//    _txtYear.inputAccessoryView = [self generateAccessoryView];
//    _txtMonth.inputAccessoryView = [self generateAccessoryView];
    
    _btnConfirm.enabled = NO;

}


- (void)initTextField:(UITextField*)textField {
    
    textField.delegate = self;
    textField.keyboardType = UIKeyboardTypeDefault;
    textField.returnKeyType = UIReturnKeyNext;
    
    if ([textField isEqual:_txtDay]) {
        
        textField.returnKeyType = UIReturnKeyDone;
    }
}

// 퀴즈 목록 요청
- (void)requestQuizList {
    
    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];
    }];
    
}

// 퀴즈 목록가져온 후 선택한 퀴즈 입력 설정
-(void)showQuizList{
    
    [[JDFacade facade] selectDatas:self listInfo:_quizList completion:^(DataSelectModel *seleced) {
        
        _selectedQuiz = seleced;
        _txtQuizInput.text = _selectedQuiz.title;
        
        QuizModel *info = (QuizModel *)_selectedQuiz.value;
        _txtQuizInput.text = _selectedQuiz.title;
        
        _btnConfirm.enabled = _selectedQuiz != nil && _txtYear.text.length >= 4 && _txtMonth.text.length >= 2 && _txtDay.text.length >=2;
        
        
        if (EQUALS(info.statusCode, @"1")) {
 
         [[JDFacade facade] alert:@"회원에 의해 직접 입력된 인증 퀴즈는 보안을 위해 문제를 보여드리지 않습니다. 정답으로 설정한 날짜를 입력하세요."];
            
        }
        
    }];
}

// 키보드 출력 시 다음,닫기 버튼 추가
- (UIView *)generateAccessoryView {
    
    CGFloat width = [UIScreen mainScreen].bounds.size.width;
    _toolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0.0, 0.0, width, 44.0)];
    _toolBar.barStyle = UIBarStyleBlack;
    _toolBar.translucent = YES;
    
    _barItems = [NSMutableArray new];
    
    _btnFlexibleSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    
    _btnKeyboardNext = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"다음", @"다음")
                                                        style:UIBarButtonItemStylePlain
                                                       target:self
                                                       action:@selector(goNextField)];
    
    
    _btnKeyboardClose = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"닫기", @"닫기")
                                                         style:UIBarButtonItemStylePlain
                                                        target:self
                                                        action:@selector(hideKeyboard)];
    
    _btnKeyboardClose.tintColor = [UIColor whiteColor];
    _btnKeyboardNext.tintColor = [UIColor whiteColor];
    
    [_barItems addObject:_btnKeyboardClose];
    [_barItems addObject:_btnFlexibleSpace];
    [_barItems addObject:_btnKeyboardNext];
    [_toolBar setItems:_barItems animated:YES];
    
    return _toolBar;
}

// 키보드에서 다음버튼 터치시 이동 설정
- (void)goNextField {
    
    if ([_txtYear isEditing]) {
        [_txtMonth becomeFirstResponder];
        return;
    }
    
    if ([_txtMonth isEditing]) {
        [_txtDay becomeFirstResponder];
        return;
    }
}

// 키보드에서 닫기버튼 터치시 키보드 내려감
- (void)hideKeyboard {
    
    [_txtYear resignFirstResponder];
    [_txtMonth resignFirstResponder];
    [_txtDay resignFirstResponder];
}



#pragma mark - User Action
- (IBAction)btnCancelTouched:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (IBAction)btnConfirmTouched:(id)sender {
    
    [self requestFindPW] ;

}


#pragma mark - textfield delegate
- (void)moveToPrevField:(id)sender {
    
    UITextField *tf = sender;
    NSInteger tag = tf.tag;
    
    if ( ![tf isEqual:_txtYear] ) {
        
        UITextField *prevTf = [self.view viewWithTag:tag - 1] ;
        [prevTf becomeFirstResponder] ;
        
    }
    
}

- (void)moveToNextField:(id)sender {
    
    UITextField *tf = sender;
    NSInteger tag = tf.tag;
    
    if ( ![tf isEqual:_txtDay] ) {
        
        UITextField *prevTf = [self.view viewWithTag:tag + 1] ;
        [prevTf becomeFirstResponder] ;
        
    }
    
}

// 퀴즈선택 TextField 터치시 퀴즈 목록 출력
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    
    if ([textField isEqual:_txtQuizInput]) {
        
        [self showQuizList];
        return NO;
    }
    return YES;
}

// 년,월,일 입력 될 시 다음버튼 활성화
- (void)textFieldDidEndEditing:(UITextField *)textField{
    // 월 입력시 1자리만 입력 된 경우 앞자리에 0추가
    if (_txtMonth.text.length == 1) {
        _txtMonth.text = [NSString stringWithFormat:@"0%@",_txtMonth.text];
    }
    
    // 일 입력시 1자리만 입력 된 경우 앞자리에 0추가
    if (_txtDay.text.length == 1) {
        _txtDay.text = [NSString stringWithFormat:@"0%@",_txtDay.text];
    }
    
    //년 4글자, 월 2글자, 일 2글자 입력시 다음 버튼 활성화
    _btnConfirm.enabled = _selectedQuiz != nil && _txtYear.text.length >= 4 && _txtMonth.text.length >= 2 && _txtDay.text.length >=2;
}

// 년,월,일 최대 입력 글자 설정
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    if ([textField isEqual:_txtYear]) {
        if (textField.text.length >= 4 && range.length == 0) {
            return NO;
        }
    } else if([textField isEqual:_txtMonth] || [textField isEqual:_txtDay]){
        if (textField.text.length >= 2 && range.length == 0) {
            return NO;
        }
    }
    
    return YES;
}


//비밀번호 찾기 요청
- (void)requestFindPW {
    
    QuizModel *info = (QuizModel *)_selectedQuiz.value;
    NSString *answer = [NSString stringWithFormat:@"%@%@%@", _txtYear.text, _txtMonth.text, _txtDay.text] ;
    
    NSString *path = [NSString stringWithFormat:API_POST_PW_FIND, _memberId];
    NSDictionary *parameter = @{@"phone" : _phoneNumber,
                                @"quiz_id" : info.quizId,
                                @"answer" : answer};
    
    [[RequestHandler handler] sendAsyncPostRequestAPIPath:path parameters:parameter modelClass:[FindIdPwModel class] completion:^(id responseObject) {
        
        FindIdPwModel *findPwModel = (FindIdPwModel *)responseObject;

        PwFindCompleteViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"PwFindCompleteViewController" storyboardName:@"SignUp"];
        vc.findPwModel = findPwModel;
        vc.memberId = _memberId;
        vc.phone = _phoneNumber;
        vc.quiz_id = info.quizId;
        vc.answer = answer;
        
        [self.navigationController pushViewController:vc animated:YES];
        
    } failure:^(id errorObject) {
        
        JDErrorModel *error = (JDErrorModel *)errorObject;
        [[JDFacade facade] alert:error.errorMessage];
        
        
    }];
    
}

@end
