//
//  ChangeEmailViewController.m
//  kneet
//
//  Created by Jason Lee on 5/13/15.
//  Copyright (c) 2015 ntels. All rights reserved.
//
#import "JDObject.h"

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


@interface ChangeEmailViewController () <CustomTextFieldDelegate> {

}
@end


#pragma mark - Class Definition

@implementation ChangeEmailViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    [self initUI];
    [self prepareViewDidLoad];
}


- (void)initUI {
    self.title = NSLocalizedString(@"이메일 변경",nil);

    
    

    _txtUserEmail.customTextFieldSuperview = CustomTextFieldSuperviewIsScrollView;
    _txtUserEmail.delegate = self;
    _txtUserEmail.keyboardType = UIKeyboardTypeEmailAddress;
    _txtUserEmail.returnKeyType = UIReturnKeyDone;
    
    //Localization
    _txtUserEmail.placeholder = NSLocalizedString(@"이메일 입력", @"이메일 입력");
    _lblTitle.text = NSLocalizedString(@"변경할 이메일 주소를 입력하세요", @"변경할 이메일 주소를 입력하세요");
    _lblDesc1.text = NSLocalizedString(@"새로운 이메일 주소로 인증메일을 발송합니다", @"새로운 이메일 주소로 인증메일을 발송합니다");
    _lblDesc2.text = NSLocalizedString(@"인증메일은 24시간 동안만 유효하며,\n인증을 마치기 전까지는\n이메일이 변경되지 않습니다", @"인증메일은 24시간 동안만 유효하며,\n인증을 마치기 전까지는\n이메일이 변경되지 않습니다");
    
    [_btnConfirm setTitle:NSLocalizedString(@"인증메일발송", @"인증메일발송") forState:UIControlStateNormal];
    [_btnCancel setTitle:NSLocalizedString(@"취소", @"취소") forState:UIControlStateNormal];
}
- (void)prepareViewDidLoad {

}

#pragma mark - Main Logic
- (void)requestChangeEmail {
    //parameters
    NSDictionary *parameter = @{@"new_email_id": _txtUserEmail.text};

    NSString *path = [NSString stringWithFormat:API_POST_MEMBER_UPDATE, [JDFacade facade].loginUser.memberId, @"email"];

    [[RequestHandler handler] sendAsyncPostRequestAPIPath:path parameters:parameter modelClass:[JDJSONModel class] completion:^(id responseObject) {
        if (!responseObject) {//응답결과가 잘못되었거나 없을 경우,
            return;
        }

        JDJSONModel *result = (JDJSONModel *) responseObject;

        if (result) {//API 성공 ,

            [JDFacade facade].loginUser.newEmailId = _txtUserEmail.text;

            [[JDFacade facade] alert:NSLocalizedString(@"인증메일이 발송되었습니다\n인증메일을 확인 후\n새로운 이메일로 로그인하세요", nil) completionHander:^{

                NSInteger count = self.navigationController.viewControllers.count;
                UIViewController *vc = self.navigationController.viewControllers[count-2];
                [self.navigationController popToViewController:vc animated:YES];
            }];
        }
    } failure:^(id errorObject) {
        JDErrorModel *error = (JDErrorModel *)errorObject;
        [[JDFacade facade] alert:error.errorMessage];
    }];
}


#pragma mark - UI Events
- (IBAction)btnConfirmTouched:(id)sender {
    //validate
    if (![ValidateUtil validateTextfiled:_txtUserEmail type:ValidateTypeEmail title:NSLocalizedString(@"이메일", @"이메일")]) {
        return;
    }

    [self requestChangeEmail];
}

- (IBAction)btnCancelTouched:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark - CustomTextField
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [self btnConfirmTouched:nil];

    return YES;
}



#pragma mark - MemoryWarning
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
