//
//  SignUpViewController.m
//  kneet
//
//  Created by Jason Lee on 4/23/15.
//  Copyright (c) 2015 ntels. All rights reserved.
//

#import "CustomLabel.h"
#import "CustomCheckBox.h"

#import "SignUpViewController.h"
#import "JDObject.h"
#import "CustomTextField.h"
#import "ValidateUtil.h"
#import "RequestHandler.h"
#import "JDJSONModel.h"
#import "WebBrowseViewController.h"
#import "CustomButton.h"

@interface SignUpViewController () {

}
@end


#pragma mark - Class Definition

@implementation SignUpViewController


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

    [self initUI];
    [self prepareViewDidLoad];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    self.title = NSLocalizedString(@"AoTHome 가입", @"AoTHome 가입");
}

- (void)initUI {
    
    
    
    
    [_lblTermUse setText:NSLocalizedString(@"이용약관 동의", @"이용약관 동의")];
    [_lblPolicy setText:NSLocalizedString(@"개인정보 취급정책 동의", @"개인정보 취급정책 동의")];
    [_lblLocation setText:NSLocalizedString(@"위치정보 활용 동의", @"위치정보 활용 동의")];
    [_lblMinor setText:NSLocalizedString(@"14세 미만인가요?", @"14세 미만인가요?")];

    [_lblTermUse setUnderLine:_lblTermUse.text];
    [_lblPolicy setUnderLine:_lblPolicy.text];
    [_lblLocation setUnderLine:_lblLocation.text];
    [_lblMinor setUnderLine:_lblMinor.text];

    [_lblTermUse addTouchEventHandler:^{
        [self showTermUse];
    }];

    [_lblPolicy addTouchEventHandler:^{
        [self showPolicy];
    }];

    [_lblLocation addTouchEventHandler:^{
        [self showLocation];
    }];

    [_lblMinor addTouchEventHandler:^{
        [self showMinor];
    }];


    _txtUserEmail.keyboardType = UIKeyboardTypeEmailAddress;
    _txtUserEmail.returnKeyType = UIReturnKeyDone;

    _txtUserName.keyboardType = UIKeyboardTypeDefault;
    _txtUserName.returnKeyType = UIReturnKeyDone;

    _txtPasswd.keyboardType = UIKeyboardTypeDefault;
    _txtPasswd.returnKeyType = UIReturnKeyDone;
    _txtPasswd.secureTextEntry = YES;

    _txtPasswdConfirm.keyboardType = UIKeyboardTypeDefault;
    _txtPasswdConfirm.secureTextEntry = YES;
    _txtPasswdConfirm.returnKeyType = UIReturnKeyDone;

    //Localization
    _txtUserName.placeholder = NSLocalizedString(@"이름", @"이름");
    _txtUserEmail.placeholder = NSLocalizedString(@"이메일", @"이메일");
    _txtPasswd.placeholder = NSLocalizedString(@"비밀번호", @"비밀번호");
    _txtPasswdConfirm.placeholder = NSLocalizedString(@"비밀번호 확인", @"비밀번호 확인");
    
    _lblUserName.text = NSLocalizedString(@"홈 멤버끼리는 이름으로 보여집니다", @"홈 멤버끼리는 이름으로 보여집니다");
    _lblUserEmail.text = NSLocalizedString(@"이메일은 로그인과 비밀번호 찾기 등\n서비스 이용 인증이 필요한 경우에 사용됩니다", @"이메일은 로그인과 비밀번호 찾기 등\n서비스 이용 인증이 필요한 경우에 사용됩니다");    
    _lblPasswd.text = NSLocalizedString(@"영어, 숫자, 특수문자 중 2가지 이상을\n사용해서 8글자 이상으로 만들어주세요", @"영어, 숫자, 특수문자 중 2가지 이상을\n사용해서 8글자 이상으로 만들어주세요");
    
    [_btnSignUp setTitle:NSLocalizedString(@"가입하기", @"가입하기") forState:UIControlStateNormal];
}

- (void)prepareViewDidLoad {

}

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

//    UIViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"SignUpInfoViewController" storyboardName:@"SignUp"];
//    [self.navigationController pushViewController:vc animated:YES];
//    return;

// get gmt time like +09:00
//    float timezoneoffset = ([[NSTimeZone systemTimeZone] secondsFromGMT] / 3600.0);
//
//    NSDateComponents *ds = [CommonUtil dateComponents:[NSDate date]];
//    ds.hour = (NSInteger)timezoneoffset;

//    NSDate *tmpDate = [[NSCalendar currentCalendar] dateFromComponents:ds];
//    NSDateFormatter *dateFormat = [CommonUtil dateFormatter];
//    [dateFormat setDateFormat:@"Z"];
//    NSMutableString *dateString = [NSMutableString stringWithString:[dateFormat stringFromDate:[NSDate date]]];
//    [dateString insertString:@":" atIndex:dateString.length-2];

    //parameters
    NSDictionary *parameter = @{@"nickname" : _txtUserName.text,
                                @"email_id" : _txtUserEmail.text,
                                @"password" : _txtPasswd.text,
                                @"service_id" : MOBILE_SERVICE_ID,
                                @"os_type" : MOBILE_DEVICE_TYPE,
                                @"country_code" : [CommonUtil countryCode],
                                @"timezone_name": [NSTimeZone localTimeZone].name};

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

        LoginModel *result = (LoginModel *) responseObject;

        if (result) {//API 성공 ,
            //이메일, 이메일 키 저장
            [JDFacade facade].tmpEmailId = _txtUserEmail.text;


            UIViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"SignUpInfoViewController" storyboardName:@"SignUp"];
            [self.navigationController pushViewController:vc animated:YES];
        }
    } failure:^(id errorObject) {
        JDErrorModel *error = (JDErrorModel *)errorObject;
        [[JDFacade facade] alert:error.errorMessage];
    }];

}


#pragma mark - UI Events
- (void)showTermUse {
    WebBrowseViewController *vc = (WebBrowseViewController *)[CommonUtil instantiateViewControllerWithIdentifier:@"WebBrowseViewController" storyboardName:@"Common"];
    vc.titleString = NSLocalizedString(@"서비스 이용약관", @"서비스 이용약관");
    
    vc.URLString = [NSString stringWithFormat:@"%@/guide/service", kAPIServer];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)showPolicy {
    WebBrowseViewController *vc = (WebBrowseViewController *)[CommonUtil instantiateViewControllerWithIdentifier:@"WebBrowseViewController" storyboardName:@"Common"];
    vc.titleString = NSLocalizedString(@"개인정보 취급정책", @"개인정보 취급정책");
    
    vc.URLString = [NSString stringWithFormat:@"%@/guide/policy", kAPIServer];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)showLocation {
    WebBrowseViewController *vc = (WebBrowseViewController *)[CommonUtil instantiateViewControllerWithIdentifier:@"WebBrowseViewController" storyboardName:@"Common"];
    vc.titleString = NSLocalizedString(@"위치기반 서비스 이용약관", @"위치기반 서비스 이용약관");
    
    vc.URLString = [NSString stringWithFormat:@"%@/guide/geo", kAPIServer];
    [self.navigationController pushViewController:vc animated:YES];

}

- (void)showMinor {
    [[JDFacade facade] alert:NSLocalizedString(@"만14세 미만이 가입할 때에는 부모님께 도움을 받으세요\n부모님이 동의하지 않을 경우 이용이 제한될 수 있습니다", @"만14세 미만이 가입할 때에는 부모님께 도움을 받으세요\n부모님이 동의하지 않을 경우 이용이 제한될 수 있습니다")];
}

- (IBAction)btnMinorTouched:(id)sender {
    [self showMinor];
}

- (IBAction)btnSignUpTouched:(id)sender {
#ifndef DEBUG
    //validate
    NSString *warn = NSLocalizedString(@"미입력 또는 미동의 항목이 남아있습니다\n확인해주세요", @"미입력 또는 미동의 항목이 남아있습니다\n확인해주세요");

    NSString *tmpUserName = [_txtUserName.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

    if ([tmpUserName isEmptyString]) {
        [[JDFacade facade] alert:warn];
        return;
    }

    if (![ValidateUtil validateTextfiled:_txtUserEmail type:ValidateTypeEmail title:NSLocalizedString(@"이메일", @"이메일")]) {
        return;
    }

    if (![ValidateUtil validateTextfiled:_txtPasswd type:ValidateTypePassword title:NSLocalizedString(@"비밀번호", @"비밀번호")]) {
        return;
    }

    if (![_txtPasswd.text isEqualToString:_txtPasswdConfirm.text]) {
        [[JDFacade facade] alert:NSLocalizedString(@"비밀번호와 비밀번호 확인이 일치하지 않습니다\n다시 시도해주세요", @"비밀번호와 비밀번호 확인이 일치하지 않습니다\n다시 시도해주세요")];
        return;
    }

    if (!_chkTermUse.checked) {
        [[JDFacade facade] alert:warn];
        return;
    }

    if (!_chkPolicy.checked) {
        [[JDFacade facade] alert:warn];
        return;
    }

    if (!_chkLocation.checked) {
        [[JDFacade facade] alert:warn];
        return;
    }
#else
    if ([_txtUserEmail.text isEmptyString]) {
        NSInteger rand = [CommonUtil dateComponents:[NSDate date]].second;
        _txtUserEmail.text = [NSString stringWithFormat:@"evoue%zd@ncomz.com", rand];
    }
    
    if ([_txtUserName.text isEmptyString]) {
        _txtUserName.text = @"이형석";
    }
    
    _txtPasswd.text = @"goj132!#@";

#endif

    [self requestSignUp];
}

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

@end
