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

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

#import "CustomLabel.h"
#import "CustomCheckBox.h"
#import "CustomTextField.h"
#import "CustomButton.h"
#import "ValidateUtil.h"

#import "WebBrowseViewController.h"
#import "SignUpViewController.h"

@implementation SignUpProfileTableViewCell

@end

@implementation SignUpNameTableViewCell

- (void)didMoveToSuperview {
    _txtName.placeholder = NSLocalizedString(@"이름", @"이름");
    
    _txtName.autoScrollUp = YES;
    _txtName.customTextFieldSuperview = CustomTextFieldSuperviewIsViewController;
}

@end


@implementation SignUpEmailTableViewCell

- (void)didMoveToSuperview {
    _txtEmail.placeholder = NSLocalizedString(@"이메일", @"이메일");
    
    _txtEmail.autoScrollUp = YES;
    _txtEmail.customTextFieldSuperview = CustomTextFieldSuperviewIsViewController;
}

@end


@implementation SignUpPasswdTableViewCell

- (void)didMoveToSuperview {
    _txtPasswd.placeholder = NSLocalizedString(@"비밀번호", @"비밀번호");
    
    _txtPasswd.autoScrollUp = YES;
    _txtPasswd.customTextFieldSuperview = CustomTextFieldSuperviewIsViewController;
}

@end


@implementation SignUpPGuideTableViewCell

@end

@implementation SignUpPasswdConfirmTableViewCell

- (void)didMoveToSuperview {
    _txtPasswdConfirm.placeholder = NSLocalizedString(@"비밀번호 확인", @"비밀번호 확인");
    
    _txtPasswdConfirm.autoScrollUp = YES;
    _txtPasswdConfirm.customTextFieldSuperview = CustomTextFieldSuperviewIsViewController;
}


@end


@interface SignUpViewController () {
    CustomTextField *_txtUserName, *_txtUserEmail, *_txtPasswd, *_txtPasswdConfirm;
    CustomButton *_btnProfile;
}
@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 {
    

    _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
    [_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];
}

- (IBAction)btnCancelTouched:(id)sender {
}

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


@end
