//
//  ChangeEmailPopupView.m
//  SmartCity
//
//  Created by Jason Lee on 01/14/16.
//  Copyright (c) 2016 ntels. All rights reserved.
//
#import "JDObject.h"

#import "RequestHandler.h"
#import "JDJSONModel.h"

#import "CustomLabel.h"
#import "CustomTextField.h"

#import "ValidateUtil.h"
#import "ChangeEmailPopupView.h"

@interface ChangeEmailPopupView () <CustomTextFieldDelegate>
{

}

@end

@implementation ChangeEmailPopupView

- (id)initFromNib {

    for (UIView *view in [CommonUtil nibViews:@"ChangeEmailPopupView"]) {
        if ([view isKindOfClass:[ChangeEmailPopupView class]]) {
            self = (ChangeEmailPopupView *)view;

            //XIB의 경우, 현재 화면 사이즈로 맞춰줘야 함.
            self.frame = [UIScreen mainScreen].bounds;
            
            _txtTempEmail.keyboardType = UIKeyboardTypeEmailAddress;
            _txtTempEmail.returnKeyType = UIReturnKeyDone;
            
            //Localization
            [self.btnConfirm setTitle:NSLocalizedString(@"확인", @"확인") forState:UIControlStateNormal];
            [self.btnCancel setTitle:NSLocalizedString(@"취소", @"취소") forState:UIControlStateNormal];
        }
    }

    return self;
}

- (void)didMoveToSuperview {
    _txtTempEmail.customTextFieldSuperview = CustomTextFieldSuperviewIsPopupContentView;
}

#pragma mark - Main Logic
- (void)requestChangeEmail {
    //parameters
    NSDictionary *parameter = @{@"new_email_id": _txtTempEmail.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) {
        
        [JDFacade facade].tmpEmailId = _txtTempEmail.text;

        [super btnConfirmTouched:nil];
        
        NSString *message1 = [NSString stringWithFormat:@"%@에서\n인증 메일을 확인하세요", [JDFacade facade].tmpEmailId];
        NSString *message2 = @"\n\n메일을 확인할 수 없는 경우에는\n스팸 메일함을 확인해보세요";
        CustomAlertView *alert = [[CustomAlertView alloc] initWithTitle:@"메일을 확인하세요" message:[NSString stringWithFormat:@"%@%@", message1, message2] delegate:nil OKButtonTitle:@"확인" cancelButtonTitle:nil];
        [alert.lblMessage1 setColor:kUITextColor02 text:message1];
        [alert show];

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


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


#pragma mark - CustomTextField

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if ([textField isEqual:_txtTempEmail]) {
        [self btnConfirmTouched:nil];
    }

    return YES;
}


@end
