//
//  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 "UIButton+WebCache.h"


#import "WebBrowseViewController.h"
#import "SignUpViewController.h"
#import "ImageUtil.h"
#import "CustomAlertView.h"

@implementation SignUpProfileTableViewCell

@end

@implementation SignUpNameTableViewCell

- (void)didMoveToSuperview {
    _txtNickname.placeholder = NSLocalizedString(@"이름", @"이름");
    
    _txtNickname.keyboardType = UIKeyboardTypeDefault;
    _txtNickname.returnKeyType = UIReturnKeyDone;

    
    _txtNickname.autoScrollUp = YES;
    _txtNickname.customTextFieldSuperview = CustomTextFieldSuperviewIsViewController;
}

@end


@implementation SignUpEmailTableViewCell

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

@end


@implementation SignUpPasswdTableViewCell

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

@end


@implementation SignUpPGuideTableViewCell

@end

@implementation SignUpPasswdConfirmTableViewCell

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


@end


@interface SignUpViewController () <ImageUtilDelegate, CustomTextFieldDelegate> {
    CustomTextField *_txtNickname, *_txtEmail, *_txtPasswd, *_txtPasswdConfirm;
    CustomButton *_btnProfile;
    
    ImageUtil *_imageUtil;
}
@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];
    
}

- (void)initUI {
    
    [self initTableViewAsDefaultStyle:_tableView];
    
    _txtPasswd.customTextFieldSuperview = CustomTextFieldSuperviewIsChildViewController;

    //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" : _txtNickname.text,
                                @"email_id" : _txtEmail.text,
                                @"password" : _txtPasswd.text,
                                @"service_id" : MOBILE_SERVICE_ID,
                                @"os_type" : MOBILE_DEVICE_TYPE,
                                @"country_code" : [CommonUtil countryCode],
                                @"timezone_name": [NSTimeZone localTimeZone].name,
                                @"image_file": [_btnProfile backgroundImageForState:UIControlStateNormal]};

    [[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 = _txtEmail.text;

            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 showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
                if (buttonIndex == 0) {//OK
                    [[JDFacade facade] dismissModalStack:YES completion:nil];
                }
            }];
        }
    } failure:^(id errorObject) {
        JDErrorModel *error = (JDErrorModel *)errorObject;
        [[JDFacade facade] alert:error.errorMessage];
    }];

}

#pragma mark - UITableView DataSource & Delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 6;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat height = 40.0f;
    
    if (indexPath.row == 0) {
        height = 120.0f;
    }
    
    return height;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = nil;
    
    if (indexPath.row == 0) {
        
        SignUpProfileTableViewCell *tcell = (SignUpProfileTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"ProfileCellIdentifier"];
        if (!_btnProfile) {
            _btnProfile = tcell.btnProfile;
        }
        if (![_btnProfile actionsForTarget:self forControlEvent:UIControlEventTouchUpInside]) {
            [_btnProfile addTarget:self action:@selector(btnProfileTouched:) forControlEvents:UIControlEventTouchUpInside];
        }
        
        if (![tcell.btnSetProfile actionsForTarget:self forControlEvent:UIControlEventTouchUpInside]) {
            [tcell.btnSetProfile addTarget:self action:@selector(btnProfileTouched:) forControlEvents:UIControlEventTouchUpInside];
        }
        
        cell = tcell;
        
    } else if (indexPath.row == 1) {
        SignUpNameTableViewCell *tcell = (SignUpNameTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"NameCellIdentifier"];
        if (!_txtNickname) {
            _txtNickname = tcell.txtNickname;
            _txtNickname.delegate = self;
        }
        
        cell = tcell;
    } else if (indexPath.row == 2) {
        SignUpEmailTableViewCell *tcell = (SignUpEmailTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"EmailCellIdentifier"];
        if (!_txtEmail) {
            _txtEmail = tcell.txtEmail;
            _txtEmail.delegate = self;
        }
        
        cell = tcell;
        
    } else if (indexPath.row == 3) {
        SignUpPasswdTableViewCell *tcell = (SignUpPasswdTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"PasswdCellIdentifier"];
        if (!_txtPasswd) {
            _txtPasswd = tcell.txtPasswd;
            _txtPasswd.delegate = self;
        }
        cell = tcell;
    } else if (indexPath.row == 4) {
        SignUpPGuideTableViewCell *tcell = (SignUpPGuideTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"PGuideCellIdentifier"];
        cell = tcell;
        
    } else if (indexPath.row == 5) {
        SignUpPasswdConfirmTableViewCell *tcell = (SignUpPasswdConfirmTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"PasswdConfirmCellIdentifier"];
        if (!_txtPasswdConfirm) {
            _txtPasswdConfirm = tcell.txtPasswdConfirm;
            _txtPasswdConfirm.delegate = self;
        }
        
        cell = tcell;
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [super tableView:tableView didSelectRowAtIndexPath:indexPath];
}


#pragma mark - ImageUtil Delegate
- (void)didFinishPickingImage:(UIImage *)image {
    
//    UIImage *maskImage = [ImageUtil resizeImage:[UIImage imageNamed:@"common_mask_circle"] width:65 height:65];
//    UIImage *thumbImage = [ImageUtil getMaskedImageWithSourchImage:image andMaskImage:maskImage];
    
    [_btnProfile setBackgroundImage:image forState:UIControlStateNormal];
}

#pragma mark - UI Events
- (void)btnProfileTouched:(id)sender {
    if (!_imageUtil) {
        _imageUtil = [[ImageUtil alloc] init];
        _imageUtil.delegate = self;
    }
    
    [_imageUtil prepareImagePicker:self];
}

- (IBAction)btnSignUpTouched:(id)sender {
#ifndef DEBUG
    if (![ValidateUtil validateTextfiled:_txtNickname type:ValidateTypeNickname title:@"이름"]) {
        return;
    }
    
    if (![ValidateUtil validateTextfiled:_txtEmail type:ValidateTypeEmail title:NSLocalizedString(@"이메일", @"이메일")]) {
        return;
    }
    
    if (![ValidateUtil validateTextfiled:_txtPasswd type:ValidateTypePassword title:NSLocalizedString(@"비밀번호", @"비밀번호")]) {
        return;
    }
    
    if (![_txtPasswd.text isEqualToString:_txtPasswdConfirm.text]) {
        [[JDFacade facade] alert:NSLocalizedString(@"두 비밀번호가 일치하지 않습니다", @"두 비밀번호가 일치하지 않습니다")];
        return;
    }
#else
    if ([_txtEmail.text isEmptyString]) {
        NSInteger rand = [CommonUtil dateComponents:[NSDate date]].second;
        _txtEmail.text = [NSString stringWithFormat:@"evoue%zd@ncomz.com", rand];
    }
    
    if ([_txtNickname.text isEmptyString]) {
        _txtNickname.text = @"이형석";
    }
    
    _txtPasswd.text = @"goj132!#@";

#endif

    [self requestSignUp];
}

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

#pragma mark - CustomTextField Delegate
- (void)textFieldDidEndEditing:(UITextField *)textField {
//    if ([_txtNickname isEqual:textField]) {
//        [ValidateUtil validateTextfiled:_txtNickname type:ValidateTypeNickname title:@"이름"];
//
//    } else if ([_txtEmail isEqual:textField]) {
//        [ValidateUtil validateTextfiled:_txtEmail type:ValidateTypeEmail title:NSLocalizedString(@"이메일", @"이메일")];
//        
//    } else if ([_txtPasswd isEqual:textField]) {
//        [ValidateUtil validateTextfiled:_txtPasswd type:ValidateTypePassword title:NSLocalizedString(@"비밀번호", @"비밀번호")];
//        
//    } else if ([_txtPasswdConfirm isEqual:textField]) {
//        [ValidateUtil validateTextfiled:_txtPasswdConfirm type:ValidateTypePassword title:NSLocalizedString(@"비밀번호 확인", @"비밀번호 확인")];
//    }
}

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


@end
