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

#import "CertificationViewController.h"
#import "CustomButton.h"
#import "CustomTextField.h"
#import "RequestHandler.h"
#import "SignUpQuizSetViewController.h"
#import "QuizViewController.h"

#define kiZeroHeight           0;
#define kiViewHeight          14; // 전송 버튼 위 여백뷰 높이 값
#define kiBtnSendHeight       50; // 전송 버튼 높이 값
#define ksSimpleSignUp      @"2"; // 일반 회원가입
#define ksMasterSignUP      @"3"; // 마스터 회원가입

@interface CertificationViewController () <CustomTextFieldDelegate>{
    
    NSString *signType;
    BOOL certificate;
    BOOL isMaster;
}

@end

@implementation CertificationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initUI];
}

// UI 설정
- (void)initUI {
    
    [self.navigationController.navigationBar setHidden:YES];
    self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    
    certificate = NO;
    _btnSend.enabled = _btnNext.enabled = NO;
    
    [_lblStep setColor:kUITextColor03 text:[NSString stringWithFormat:@"%@", @"/ 5"]];
    
    [self initTextField:_txtPhoneNum];
    [self initTextField:_txtCertifyInput];
    
    
    [self.btnSend setBackgroundImage:[UIImage imageNamed:@"img_btn_common_active"] forState:UIControlStateNormal capInsets:UIEdgeInsetsMake(kfTopInset,kfRightInset,kfBottomInset,kfLeftInset)];
    
    [self.btnSend setBackgroundImage:[UIImage imageNamed:@"img_btn_common_press"] forState:UIControlStateHighlighted capInsets:UIEdgeInsetsMake(kfTopInset,kfRightInset,kfBottomInset,kfLeftInset)];
    
    [self.btnSend setBackgroundImage:[UIImage imageNamed:@"img_btn_common_disable"] forState:UIControlStateDisabled capInsets:UIEdgeInsetsMake(kfTopInset,kfRightInset,kfBottomInset,kfLeftInset)];
    
    
    // 마스터,멤버 여부에 따라 전송 버튼 Hidden 여부설정
    isMaster = [[JDFacade facade].signType isEqualToString:KNEET_MEMBER_MASTER] ;
    [self hiddenSendButton:isMaster];
    
    
}

- (void)initTextField:(UITextField*)textFiled {
    
    textFiled.returnKeyType = UIReturnKeyDone;
    textFiled.keyboardType = UIKeyboardTypeNumberPad;
    textFiled.delegate = self;
}


// 휴대폰 번호 인증 확인 요청
- (void)requestValidNum {
    
    NSDictionary *parameter = @{@"phone":  _txtPhoneNum.text,
                                @"auth_number" : _txtCertifyInput.text,
                                @"send_type" :  @"U",
                                @"auth_type" :  signType};
    
    NSString *path = API_POST_RESPONSE_AUTH_NUM;
    
    [[RequestHandler handler] sendAsyncPostRequestAPIPath:path parameters:parameter modelClass:[SignUpModel class] completion:^(id responseObject) {
        
        SignUpModel *signUpModel = (SignUpModel *)responseObject;
        
        //NSLog(@"Response : %@",signUpModel);
        
        // 마스터 회원가입일 경우 퀴즈 선택 메뉴로 이동
        if ([[JDFacade facade].signType isEqualToString:KNEET_MEMBER_MASTER]) {
            
            SignUpQuizSetViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"SignUpQuizSetViewController" storyboardName:@"SignUp"];
            
            vc.signUpModel = signUpModel;
            vc.phoneNum = _txtPhoneNum.text;
            [JDFacade facade].signUpUser = signUpModel;
            
            [self.navigationController pushViewController:vc animated:YES];
            // 멤버 회원가입일 경우 퀴즈 정답 입력 메뉴로 이동
            
        } else {
            
            QuizViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"QuizViewController" storyboardName:@"SignUp"];
            
            vc.signUpModel = signUpModel;
            vc.phoneNum = _txtPhoneNum.text;
            [JDFacade facade].signUpUser = signUpModel;
            
            [self.navigationController pushViewController:vc animated:YES];
        }
        
    } failure:^(id errorObject) {
        
        JDErrorModel *error = (JDErrorModel *)errorObject;
        [[JDFacade facade] alert:error.errorMessage];
    }];
    
}

// 인증번호 전송 ( 멤버 회원가입만 해당 )
- (void)requestAuthSendNum {
    //parameters
    NSDictionary *parameter = @{@"phone": _txtPhoneNum.text,
                                @"auth_type": signType};
    
    NSString *path = API_POST_REQUEST_AUTH_NUM;
    
    [[RequestHandler handler] sendAsyncPostRequestAPIPath:path parameters:parameter modelClass:[JDJSONModel class] completion:^(id responseObject) {
        
        certificate = YES;
        _lblMessage.text = @"인증번호는 전송 후 3분 동안 유효 합니다";
        [_btnSend setTitle: @"인증번호 재전송" forState : UIControlStateNormal];
        
    } failure:^(id errorObject) {
        
        JDErrorModel *error = (JDErrorModel *)errorObject;
        [[JDFacade facade] alert:error.errorMessage];
        _lblMessage.text = error.errorMessage;
    }];
    
}

// 인증번호 전송 여부 설정
- (void)hiddenSendButton:(BOOL)isHidden{
    
    if (isHidden) {
        _btnSend.hidden = YES;
        _btnSendHeight.constant = kiZeroHeight; // 버튼 높이 값 0 설정
        _viewHeight.constant = kiZeroHeight;    // 뷰 높이 값 0 설정
        _lblMessage.text = @"설치기사님에게 인증번호 SMS를 받은 번호만\n인증이 가능합니다.";
        signType = ksMasterSignUP;              // 인증 타입 마스터로 설정
    } else {
        _btnSend.hidden = NO;
        _btnSendHeight.constant = kiBtnSendHeight; // 버튼 높이 값 50 설정
        _viewHeight.constant = kiViewHeight;       // 뷰 높이 값 14 설정
        _lblMessage.text = @"마스터 사용자에게 초대 SMS를 받은 번호만\n인증이 가능합니다.";
        signType = ksSimpleSignUp;                // 인증 타입 멤버로 설정
        
        //        _txtPhoneNum.hasMoveButton = _txtCertifyInput.hasMoveButton = NO;
        //
        //        [_txtPhoneNum refreshAccessoryView];
        //        [_txtCertifyInput refreshAccessoryView];
        
    }
}

// 다음 버튼 터치시 인증번호 유효성 체크
- (IBAction)btnNextTouched:(id)sender {
    [self requestValidNum];
}

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

// 인증 번호 전송 버튼 터치시 입력 된 휴대폰 번호로 인증번호 전송
- (IBAction)btnSendTouched:(id)sender {
    [self requestAuthSendNum];
}


#pragma mark - textfield delegate
// 휴대폰 번호 및 인증번호에 입력 된 글자 수에따라 다음 버튼 Enable여부 설정
- (void)textFieldDidEndEditing:(UITextField *)textField{
    
    // 휴대폰 번호가 10자리 이상 입력 된 경우 다음 버튼 활성화
    //    BOOL enabledPhoneNumber = _txtPhoneNum.text.length >= 10;
    //    _btnSend.enabled = enabledPhoneNumber;
    //    _btnNext.enabled = enabledPhoneNumber;
    //
    //
    // 인증번호가 4자리가 입력 된 경우 다음 버튼 활성화

    _btnNext.enabled = isMaster
                        ? _txtPhoneNum.text.length >= 10 && _txtCertifyInput.text.length >= 4
                        : certificate && _txtCertifyInput.text.length >= 4 ;
    
}

// 휴대폰 번호 및 인증번호 최대 입력가능한 텍스트 설정
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    NSString *text = [textField.text stringByReplacingCharactersInRange:range withString:string];
    
    if ([textField isEqual:_txtPhoneNum]) {
        
        _btnSend.enabled = text.length >= 10;
        certificate = NO;
    }

    // 휴대폰 번호입력 최대 11글자
    if ([textField isEqual:_txtPhoneNum] && text.length > 11) {
        
        return NO;
        
        // 인증번호 최대 4글자
    } else if([textField isEqual:_txtCertifyInput] && text.length > 4){
        
        return NO;
        
    }
    return YES;
}

//일반 회원일때
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    if ([textField isEqual:_txtPhoneNum]) {
        
        [_txtCertifyInput becomeFirstResponder];
    }
    else {
        [_txtPhoneNum becomeFirstResponder];
    }
    
    return YES ;
}

//마스터 회원일때
- (void)moveToNextField:(id)sender {
    
    [_txtCertifyInput becomeFirstResponder];
    
}

- (void)moveToPrevField:(id)sender {
    
    [_txtPhoneNum becomeFirstResponder];
}

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