//
//  ResetPwdViewController.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 "ValidateUtil.h"

#import "CustomTextField.h"
#import "CustomLabel.h"
#import "CustomButton.h"
#import "CustomAlertView.h"

#import "ResetPwdViewController.h"

@implementation ResetEmailTableViewCell

- (void)didMoveToSuperview {
}

@end

@implementation ResetPasswdTableViewCell

- (void)didMoveToSuperview {

    _txtUserEmail.autoScrollUp = YES;
    _txtUserEmail.keyboardType = UIKeyboardTypeEmailAddress;
    _txtUserEmail.returnKeyType = UIReturnKeyDone;
    _txtUserEmail.customTextFieldSuperview = CustomTextFieldSuperviewIsContentView;

    _txtUserEmail.placeholder = NSLocalizedString(@"이메일", @"이메일");
}

@end

@interface ResetPwdViewController () <CustomTextFieldDelegate> {
    CustomTextField *_txtUserEmail;
}
@end


#pragma mark - Class Definition

@implementation ResetPwdViewController


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

    [self initUI];
    [self prepareViewDidLoad];
}

- (void)initUI {
    //init table view
    [self initTableViewAsDefaultStyle:_tableView];
}

- (void)prepareViewDidLoad {

}


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

    //parameters
    NSDictionary *parameter = @{@"email_id": _txtUserEmail.text,
                                @"service_id": MOBILE_SERVICE_ID};

    NSString *path = [NSString stringWithFormat:API_POST_RESET_PWD];

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

        JDJSONModel *result = (JDJSONModel *) responseObject;

        if (result) {//API 성공 ,
            [JDFacade facade].tmpEmailId = _txtUserEmail.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 2;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat height = 225.0f;
    
    NSInteger row = indexPath.row;
    if (row == 1) {
        height = 205.0f;
    }
    
    return height;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = nil;
    NSInteger row = indexPath.row;
    
    if (row == 0) {
        ResetEmailTableViewCell *tcell = (ResetEmailTableViewCell*)[tableView dequeueReusableCellWithIdentifier:@"EmailCellIdentifier"];
        if (![tcell.btnFindId actionsForTarget:self forControlEvent:UIControlEventTouchUpInside]) {
            [tcell.btnFindId addTarget:self action:@selector(btnFindIdTouched:) forControlEvents:UIControlEventTouchUpInside];
        }
        
        cell = tcell;
    } else if (row == 1) {
        ResetPasswdTableViewCell *tcell = (ResetPasswdTableViewCell*)[tableView dequeueReusableCellWithIdentifier:@"PasswdCellIdentifier"];
        
        if (!_txtUserEmail) {
            _txtUserEmail = tcell.txtUserEmail;
        }
        
        if (![tcell.btnFindPasswd actionsForTarget:self forControlEvent:UIControlEventTouchUpInside]) {
            [tcell.btnFindPasswd addTarget:self action:@selector(btnRequestPasswdTouched:) forControlEvents:UIControlEventTouchUpInside];
        }
        
        cell = tcell;
    }
    
    return cell;
}

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



#pragma mark - UI Events
- (IBAction)btnFindIdTouched:(id)sender {
    NSString *mailto = URL_HELP_MAIL;
    NSString *url = [mailto stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
}


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

    //비밀번호 재설정 요청
    [self requestResetPassword];
}

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

#pragma mark - CustomTextField

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [self btnRequestPasswdTouched:nil];

    return YES;
}


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

@end
