//
//  NewMobileViewController.m
//  kneet
//
//  Created by Jason Lee on 4/27/15.
//  Copyright (c) 2015 ntels. All rights reserved.
//
#import "RequestHandler.h"
#import "JDJSONModel.h"

#import "CustomTextField.h"
#import "ValidateUtil.h"
#import "NewMobileViewController.h"
#import "LoginViewController.h"
#import "CustomLabel.h"
#import "CustomButton.h"


@interface NewMobileViewController () <CustomTextFieldDelegate> {

}
@end


#pragma mark - Class Definition

@implementation NewMobileViewController


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

    [self initUI];
    [self prepareViewDidLoad];
}

- (void)initUI {
    

    _txtAuthCode.delegate = self;
    _txtAuthCode.keyboardType = UIKeyboardTypeDefault;
    _txtAuthCode.returnKeyType = UIReturnKeyDone;
    _txtAuthCode.customTextFieldSuperview = CustomTextFieldSuperviewIsScrollView;
    
    //Localization
    _txtAuthCode.placeholder = NSLocalizedString(@"인증 문자 입력", @"인증 문자 입력");
    _lblTitle.text = NSLocalizedString(@"새로운 단말에서\n로그인 하셨군요!", @"새로운 단말에서\n로그인 하셨군요!");
    
    [_btnConfirm setTitle:NSLocalizedString(@"확인", @"확인") forState:UIControlStateNormal];
    [_btnCancel setTitle:NSLocalizedString(@"취소", @"취소") forState:UIControlStateNormal];
}

- (void)prepareViewDidLoad {
    
    _lblEmailInfo.text = [NSString stringWithFormat:@"본인 확인을 위해\n%@\n으로 발송된 인증 문자를\n입력하세요", [JDFacade facade].tmpEmailId];
    [_lblEmailInfo setColor:kUITextColor02 text:[JDFacade facade].tmpEmailId];
}

#pragma mark - Main Logic
- (void)requestNewDevice {

    //parameters
    NSDictionary *parameter = @{@"key": _txtAuthCode.text,
                                @"email_id": [JDFacade facade].tmpEmailId,
                                @"service_id": MOBILE_SERVICE_ID,
                                @"os_type": MOBILE_DEVICE_TYPE,
                                @"device_sn": [JDFacade facade].deviceUUID,
                                @"device_token": [JDFacade facade].APNSToken,
                                @"device_name": [CommonUtil deviceName],
                                @"replace_device_sn": _replaceDeviceSn ? _replaceDeviceSn : ksEmptyString};

    NSString *path = [NSString stringWithFormat:API_POST_NEW_MOBILE_DEVICE];

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

        LoginModel *loginInfo = (LoginModel *)responseObject;

        if (loginInfo) {//API 성공 ,함
            [[JDFacade facade] toast:@"새 단말 이용을 시작합니다"];

            LoginViewController *lvc = [[JDFacade facade] viewControllerOnPresentingViewController:self viewControllerClass:[LoginViewController class]];
            if ([lvc isKindOfClass:[LoginViewController class]]) {
                [lvc actionForLoginSucceed:loginInfo];
            }
        }

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


#pragma mark - UI Events
- (IBAction)btnConfirmTouched:(id)sender {
    //validate
    if (![ValidateUtil validateTextfiled:_txtAuthCode type:ValidateTypeNull title:NSLocalizedString(@"인증문자", @"인증문자")]) {
        return;
    }

    [self requestNewDevice];
}

- (IBAction)btnCancelTouched:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

#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
