//
//  ChangeNamePopupView.m
//  kneet2
//
//  Created by Jason Lee on 10/12/15.
//  Copyright (c) 2015 ntels. All rights reserved.
//
#import "JDObject.h"

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

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

#import "ValidateUtil.h"
#import "ChangeNamePopupView.h"

@interface ChangeNamePopupView () <CustomTextFieldDelegate>
{

}

@end

@implementation ChangeNamePopupView

- (id)initFromNib {

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

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

    return self;
}

- (void)didMoveToSuperview {
    if (!self.superview) {
        return;
    }
    _txtNickname.customTextFieldSuperview = CustomTextFieldSuperviewIsPopupContentView;
}

#pragma mark - Main Logic
- (void)requestChangeNickname {
    //parameters
    NSDictionary *parameter = @{@"nickname": _txtNickname.text};
    
    NSString *path = [NSString stringWithFormat:API_POST_MEMBER_UPDATE, [JDFacade facade].loginUser.memberId, @"name"];
    
    [[RequestHandler handler] sendAsyncPostRequestAPIPath: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.nickname = _txtNickname.text;
            
            [super btnConfirmTouched:nil];
        }
    } failure:^(id errorObject) {
        JDErrorModel *error = (JDErrorModel *)errorObject;
        [[JDFacade facade] alert:error.errorMessage];
    }];
}


#pragma mark - UI Events
- (IBAction)btnConfirmTouched:(id)sender {
    //validate
    if (![ValidateUtil validateTextfiled:_txtNickname type:ValidateTypeNickname title:NSLocalizedString(@"이름", @"이름")]) {
        return;
    }
    
    [self requestChangeNickname];
}


#pragma mark - CustomTextField

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

    return YES;
}


@end
