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

#import "TempPwViewController.h"
#import "CustomLabel.h"
#import "CustomButton.h"
#import "CustomTextField.h"
#import "RequestHandler.h"
#import "JDJSONModel.h"
#import "ValidateUtil.h"

@interface TempPwViewController ()<CustomTextFieldDelegate> {
}

@end

@implementation TempPwViewController

- (void)viewDidLoad {
    [super viewDidLoad];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

}

- (void) initUI{
    
    _btnNext.enabled = NO ;
    _txtPwInput.customTextFieldSuperview = CustomTextFieldSuperviewIsScrollView;
    _txtPwReInput.customTextFieldSuperview = CustomTextFieldSuperviewIsScrollView;
    
}

#pragma mark - API
- (void)requestSetNewPassword {
    
    NSDictionary *parameter = @{@"type": @"password",
                                @"password": _txtPwInput.text};
    
    NSString *path = [[JDFacade facade] getUrlWithCustGroupIDAndMemberID:API_PUT_MEMBER_UPDATE];

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

        [JDFacade facade].tmpPassword = nil;
        [JDFacade facade].loginUser.tempPasswordYn = @"N";
        
        [[JDFacade facade] toast:@"비밀번호를 변경했습니다"];
        
        [self moveNext];
   
    } failure:^(id errorObject) {
        
        JDErrorModel *error = (JDErrorModel *)errorObject;
        [[JDFacade facade] alert:error.errorMessage];
    }];
}

#pragma mark - textfield delegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
  
    if ([textField isEqual:_txtPwInput]) {

        [_txtPwReInput becomeFirstResponder];
        
    }
    else {
        
        [self.view endEditing:YES];
        
    }
    
    return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField{
    
    _btnNext.enabled = _txtPwInput.text.length >= 8 && _txtPwReInput.text.length >= 8 ;
    
}


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

- (IBAction)btnConfirmTouched:(id)sender {
    
//    if (![ValidateUtil validateTextfiled:_txtPwInput type:ValidateTypePassword title:NSLocalizedString(@"비밀번호", @"비밀번호")]) {
//        return;
//    }
    
    if (![_txtPwInput.text isEqualToString:_txtPwReInput.text]) {
        [[JDFacade facade] alert:@"재입력된 비밀번호가 다릅니다."];
        return;
    }
    
    [self requestSetNewPassword];
    
}


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

@end
