//
//  SettingsNumChangeViewController.m
//  OneCable
//
//  Created by nComz on 2017. 4. 19..
//  Copyright © 2017년 ntels. All rights reserved.
//

#import "SettingsNumChangeViewController.h"
#import "CustomButton.h"
#import "CustomLabel.h"
#import "CustomTextField.h"
#import "JDObject.h"
#import "RequestHandler.h"
#import "JDJSONModel.h"
#import "ValidateUtil.h"
#import "SettingsViewController.h"

@interface SettingsNumChangeViewController () <CustomTextFieldDelegate> {

    BOOL certificate;
}

@end

@implementation SettingsNumChangeViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self initUI];
}

- (void)initUI {
    UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];
    statusBar.backgroundColor = [UIColor whiteColor];
    
    _lblMessage.hidden = YES;
    _btnSend.enabled = NO;
    _btnConfirm.enabled = NO;
//    _lblRemainTime.hidden = YES;
    
    _txtInputNum.returnKeyType = UIReturnKeyDone;
    _txtInputNum.keyboardType = UIKeyboardTypeNumberPad;
    _txtInputNum.delegate = self;
    
    _txtInputAuthNum.returnKeyType = UIReturnKeyDone;
    _txtInputAuthNum.keyboardType = UIKeyboardTypeNumberPad;
    _txtInputAuthNum.delegate = self;
    
    [self.navigationController.navigationBar setHidden:YES];
    self.navigationController.interactivePopGestureRecognizer.enabled = NO;
}

- (IBAction)btnSendTouched:(id)sender {
//    //validate
//    if (![ValidateUtil validateTextfiled:_txtInputNum type:ValidateTypeNumber title:NSLocalizedString(@"이름", @"이름")]) {
//            return;
//    }
    
     [self requestAuthNum];
}

- (IBAction)btnCancelTouched:(id)sender {
    // 설정 페이지로 이동
    
    if (_isPresente)
        [self dismissViewControllerAnimated:YES completion:nil];
    else
        [[self navigationController] popToRootViewControllerAnimated:YES];
}

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

- (void)requestChangePhoneNumber {
    //parameters
    NSDictionary *parameter = @{@"phone": _txtInputNum.text,
                                @"auth_number": _txtInputAuthNum.text };
    
    NSString *path = [[JDFacade facade] getUrlWithCustGroupIDAndMemberID:API_PUT_CHANGE_PHONE_NUM];
    
    [[RequestHandler handler] sendAsyncPutRequestAPIPath:path parameters:parameter modelClass:[JDJSONModel class] completion:^(id responseObject) {
//                if (!responseObject) {//응답결과가 잘못되었거나 없을 경우,
//                    return;
//                }
//
//                JDJSONModel *result = (JDJSONModel *) responseObject;
//        
//                if (result) {//API 성공 ,
//    
//                }
        [[JDFacade facade] toast:NSLocalizedString(@"휴대폰 번호가 변경되었습니다.", nil)];
        
        [JDFacade facade].loginUser.phone = _txtInputNum.text;
 
        if (_isPresente) {
        
            [JDFacade facade].loginUser.phoneAuthYn = @"Y";
            
            [self gotoMainView];
        }
        else
            [[self navigationController] popViewControllerAnimated:YES];
        
        
    } failure:^(id errorObject) {
        
        JDErrorModel *error = (JDErrorModel *)errorObject;
        [[JDFacade facade] alert:error.errorMessage];
    }];
}

- (void)requestAuthNum {
    //parameters
    NSDictionary *parameter = @{@"cust_id": [JDFacade facade].loginUser.custId,
                                @"ctrt_grp_id": [JDFacade facade].loginUser.ctrtGrpId,
                                @"phone": _txtInputNum.text,
                                @"auth_type": @"1" };
    
    NSString *path = [NSString stringWithFormat:API_POST_REQUEST_AUTH_NUM];
    
    [[RequestHandler handler] sendAsyncPostRequestAPIPath:path parameters:parameter modelClass:[JDJSONModel class] completion:^(id responseObject) {
        NSLog(@"requestAuthNum : %@", responseObject);
        
        certificate = YES;
        
        [_btnSend setTitle: @"인증번호 재전송" forState : UIControlStateNormal];
        _lblMessage.hidden = NO;
        
    } failure:^(id errorObject) {
        
        JDErrorModel *error = (JDErrorModel *)errorObject;
        [[JDFacade facade] alert:error.errorMessage];
        _lblMessage.hidden = NO;
        _lblMessage.text = error.errorMessage;
    }];
    
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
  
    if ([textField isEqual:_txtInputNum]) {
        
        [_txtInputAuthNum becomeFirstResponder];
    }
    else {
        [_txtInputNum becomeFirstResponder];
    }

    return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField{

    _btnConfirm.enabled = certificate && _txtInputAuthNum.text.length >= 4 ;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {

    NSString *text = [textField.text stringByReplacingCharactersInRange:range withString:string];
    
    if ([textField isEqual:_txtInputNum]) {
        
        _btnSend.enabled = text.length >= 10;
        certificate = NO;
    }
    
    // 휴대폰 번호입력 최대 11글자
    if ([textField isEqual:_txtInputNum] && text.length > 11) {
        
        return NO;
        
        // 인증번호 최대 4글자
    } else if([textField isEqual:_txtInputAuthNum] && text.length > 4){
        
        return NO;
        
    }
    
    return YES;
}

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

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


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

}


- (void)gotoMainView {
    
    UIViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"MainViewController" storyboardName:@"Main"];
    
    [JDFacade facade].mainViewController = (MainViewController *)vc;
    [[JDFacade facade].appDelegate.window setRootViewController:vc];
}

@end
