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

#import "QuizViewController.h"
#import "CustomButton.h"
#import "CustomTextField.h"
#import "RequestHandler.h"
#import "IDSetViewController.h"
#import "CommonUtil.h"

/**
 해당 메뉴는 멤버만 출력
 **/
@interface QuizViewController () <CustomTextFieldDelegate>{
    UIBarButtonItem *_btnKeyboardNext, *_btnKeyboardClose;  // 키보드 출력시 다음,닫기 버튼추가
    UIToolbar *_toolBar;                                    // 툴바 설정
    NSMutableArray *_barItems;                              // 툴바에 추가할 아이템
    UIBarButtonItem *_btnFlexibleSpace;                     // 여백 설정
}

@end

@implementation QuizViewController
@synthesize signUpModel;

// 마스터가 멤버초대시 설정한 퀴즈 가져옴
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initUI];
    [self requsetMasterQuiz];
}

// UI 설정
- (void)initUI {
    [self.navigationController.navigationBar setHidden:YES];
    self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    
    signUpModel.phone = _phoneNum;
    
    _btnNext.enabled = NO;
    
    [_lblStep setColor:kUITextColor03 text:[NSString stringWithFormat:@"%@", @"/ 5"]];
  
    [self initTextField:_txtYear placeholder:[CommonUtil currentYear]];
    [self initTextField:_txtMonth placeholder:[CommonUtil currentMonth]];
    [self initTextField:_txtDay placeholder:[CommonUtil currentDay]];
    

}


- (void)initTextField:(UITextField*)textfield
          placeholder:(NSString*)placeholder {
    
    textfield.delegate = self;
    textfield.placeholder = placeholder;
    textfield.keyboardType = UIKeyboardTypeNumberPad;
    
}

// 마스터가 설정한 퀴즈의 정답 체크 후 아이디/비밀번호 설정 메뉴로 이동
- (void)requestAnswerQuiz{
    NSString *answer = [NSString stringWithFormat:@"%@%@%@",_txtYear.text,_txtMonth.text,_txtDay.text];
    //parameters
    NSDictionary *parameter = @{@"phone": signUpModel.phone ,
                                @"answer": answer};
    
    NSString *path = [[JDFacade facade]getUrlWithCustAndGroupIDAndInputMemId:API_POST_QUIZ_SEND inputId:@""];
    
    [[RequestHandler handler] sendAsyncPostRequestAPIPath:path parameters:parameter modelClass:[JDJSONModel class] completion:^(id responseObject) {

        IDSetViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"IDSetViewController" storyboardName:@"SignUp"];
        
        vc.signUpModel = signUpModel;
        
        [self.navigationController pushViewController:vc animated:YES];
        
    } failure:^(id errorObject) {
        
        JDErrorModel *error = (JDErrorModel *)errorObject;
        [[JDFacade facade] alert:error.errorMessage];
    }];
}

// 마스터가 멤버초대시 설정한 퀴즈 가져오기
- (void)requsetMasterQuiz {
    //parameters
    NSDictionary *parameter = @{@"phone": signUpModel.phone};
    
    NSString *path = [[JDFacade facade]getUrlWithCustAndGroupIDAndInputMemId:API_POST_REQUEST_QUIZ inputId:@""];

    [[RequestHandler handler] sendAsyncPostRequestAPIPath:path parameters:parameter modelClass:[QuizModel class] completion:^(id responseObject) {

        QuizModel *quizModel = (QuizModel *) responseObject;

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

// 다음 버튼 터치시 퀴즈정답 체크
- (IBAction)btnNextTouched:(id)sender {
        [self requestAnswerQuiz];
}

// 메뉴 닫기
- (IBAction)btnCancelTouched:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

// 년,월,일 입력 될 시 다음버튼 활성화
- (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글자 입력시 다음 버튼 활성화
    if (_txtYear.text.length >= 4 && _txtMonth.text.length >= 2 && _txtDay.text.length >=2){
        
        _btnNext.enabled = YES;
    } else {
        _btnNext.enabled = NO;
    }
}

// 년,월,일 최대 입력 글자 설정
- (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]){
        if (textField.text.length >= 2 && range.length == 0) {
            return NO;
        }
    } else if ([textField isEqual:_txtDay]){
        if (textField.text.length >= 2 && range.length == 0) {
            return NO;
        }
    }
    return YES;
}


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

// 키보드에서 닫기버튼 터치시 키보드 내려감
- (void)hideKeyboard {

    [_txtYear resignFirstResponder];
    [_txtMonth resignFirstResponder];
    [_txtDay resignFirstResponder];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
