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

#import "IDSetViewController.h"
#import "CustomButton.h"
#import "CustomTextField.h"
#import "RequestHandler.h"
#import "UserNameSetViewController.h"
#import "ValidateUtil.h"

@interface IDSetViewController () <CustomTextFieldDelegate>{
    
    BOOL checkID;
    
}

@end

@implementation IDSetViewController
@synthesize signUpModel;

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

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}
// UI 설정
- (void)initUI {
    
    [self.navigationController.navigationBar setHidden:YES];
    self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    
    _lblMessageId.hidden = YES;
    _btnOverlap.enabled = NO;
    _btnNext.enabled = NO;
    _txtPwInput.enabled = NO ;
    _txtPwReInput.enabled = NO ;
 
    [_lblStep setColor:kUITextColor03 text:[NSString stringWithFormat:@"%@", @"/ 5"]];
    
    [self.btnOverlap setBackgroundImage:[UIImage imageNamed:@"img_btn_common_active"] forState:UIControlStateNormal capInsets:UIEdgeInsetsMake(kfTopInset,kfRightInset,kfBottomInset,kfLeftInset)];
    
    [self.btnOverlap setBackgroundImage:[UIImage imageNamed:@"img_btn_common_press"] forState:UIControlStateHighlighted capInsets:UIEdgeInsetsMake(kfTopInset,kfRightInset,kfBottomInset,kfLeftInset)];
    
    [self.btnOverlap setBackgroundImage:[UIImage imageNamed:@"img_btn_common_disable"] forState:UIControlStateDisabled capInsets:UIEdgeInsetsMake(kfTopInset,kfRightInset,kfBottomInset,kfLeftInset)];
    
//    [self initTextField:_txtIdInput];
//    [self initTextField:_txtPwInput];
//    [self initTextField:_txtPwReInput];
    
}

//- (void)initTextField:(UITextField*)textFiled {
//    
//    
//    textFiled.keyboardType = UIKeyboardTypeDefault;
//    textFiled.delegate = self;
//}



// 아이디 중복 여부 확인
- (void)requestIdDuplicateCheck {

    NSString *path = [[JDFacade facade]getUrlWithCustAndGroupIDAndInputMemId:API_GET_ID_CHK inputId:_txtIdInput.text];
    
    [[RequestHandler handler] sendAsyncGetRequestAPIPath:path parameters:nil modelClass:[JDJSONModel class] completion:^(id responseObject) {
        
        _lblMessageId.hidden = NO;
        _txtPwInput.enabled = _txtPwReInput.enabled = YES ;
        checkID = YES;
        
    } failure:^(id errorObject) {
        
        JDErrorModel *error = (JDErrorModel *)errorObject;
        [[JDFacade facade] alert:error.errorMessage];
        _lblMessageId.hidden = YES;
        _txtIdInput.text = @"";

    }];
}

// 마스터 회원가입 요청
- (void)requestMasterSignUp {
    //parameters
    NSDictionary *parameter = @{@"member_id" : _txtIdInput.text,
                                @"phone" : signUpModel.phone,
                                @"os_type" : MOBILE_DEVICE_TYPE,
                                @"password" : _txtPwReInput.text,
                                @"quiz_id" : signUpModel.quizId,
                                @"quiz" : signUpModel.quiz,
                                @"status_code" : signUpModel.statusCode,
                                @"answer": signUpModel.answer};

    NSString *path = API_POST_MASTER_SIGN_UP;
    
    [[RequestHandler handler] sendAsyncPostRequestAPIPath:path parameters:parameter modelClass:[JDJSONModel class] completion:^(id responseObject) {
    
        UserNameSetViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"UserNameSetViewController" storyboardName:@"SignUp"];
        
        signUpModel.memberId = _txtIdInput.text;
        vc.signUpModel = signUpModel;
        
        [self.navigationController pushViewController:vc animated:YES];

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

// 멤버 회원가입 요청
- (void)requestMemberSignUp {
    //parameters
    NSDictionary *parameter = @{@"member_id": _txtIdInput.text,
                                @"phone": signUpModel.phone,
                                @"password": _txtPwReInput.text,};
    
    NSString *path = API_POST_SIMPLE_SIGN_UP;
    
    [[RequestHandler handler] sendAsyncPostRequestAPIPath:path parameters:parameter modelClass:[SignUpModel class] completion:^(id responseObject) {
        
        signUpModel = (SignUpModel*)responseObject;
        signUpModel.memberId = _txtIdInput.text;
        NSLog(@"Response Member Info : %@", signUpModel);
        
        UserNameSetViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"UserNameSetViewController" storyboardName:@"SignUp"];
        
        vc.signUpModel = signUpModel;
        [self.navigationController pushViewController:vc animated:YES];
        
    } failure:^(id errorObject) {
        
        JDErrorModel *error = (JDErrorModel *)errorObject;
        [[JDFacade facade] alert:error.errorMessage];
    }];
}

// 다음버튼 터치시 비밀번호 유효성 체크 및 회원가입 유형에 따른 회원가입 요청 설정
- (IBAction)btnNextTouched:(id)sender {

//    if (![ValidateUtil validateTextfiled:_txtPwInput type:ValidateTypePassword title:NSLocalizedString(@"비밀번호", @"비밀번호")]) {
//        return;
//    }

    if (!EQUALS(_txtPwInput.text, _txtPwReInput.text)) {
        [[JDFacade facade] alert:@"재 입력된 비밀번호가 다릅니다."];
        return;
    }

    // 마스터 회원가입
    if ([[JDFacade facade].signType isEqualToString:KNEET_MEMBER_MASTER]) {
        [self requestMasterSignUp];
    // 멤버 회원가입
    } else {
        [self requestMemberSignUp];
    }
    
}


#pragma mark - textfield delegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    NSString *text = [textField.text stringByReplacingCharactersInRange:range withString:string];
    
    
    if ([textField isEqual:_txtIdInput]) {
        
        checkID = NO;
        _txtPwReInput.enabled = _txtPwInput.enabled = NO ;
        _lblMessageId.hidden = YES ;
        _btnOverlap.enabled = text.length >= 6;
    }
    
    return YES;
}



// 아이디,비밀번호 입력시 다음버튼 활성화
- (void)textFieldDidEndEditing:(UITextField *)textField{
    
    if (_txtIdInput.text.length >= 6) {
//        _btnOverlap.enabled = YES;
    } else {
        _lblMessageId.hidden = YES;
//        _btnOverlap.enabled = NO;
    }
    
    _btnNext.enabled = checkID && _txtPwInput.text.length >= 8 && _txtPwReInput.text.length >= 8 ;
    
}

// TextField Done 버튼 설정
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    if ([textField isEqual:_txtIdInput] || [textField isEqual:_txtPwReInput]) {
        
        [textField resignFirstResponder];
    }
    else {
        
        UITextField *nextTf = [self.view viewWithTag:textField.tag + 1];
        
        [textField resignFirstResponder];
        [nextTf becomeFirstResponder];
    }
    
    return YES;
}

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

// 중복 확인 버튼 터치시
- (IBAction)btnOverlapTouched:(id)sender {
    
//    if (![ValidateUtil validateTextfiled:_txtIdInput type:ValidateTypeID title:NSLocalizedString(@"아이디", @"아이디")]) {
//        return;
//    }
    
    [self requestIdDuplicateCheck];
}
@end
