//
//  RestPassWordViewController.m
//  Project
//
//  Created by Vae on 2018/7/18.
//

#import "ResetPassWordViewController.h"
#import "Lang.h"
#import "SDK.h"
#import "BeanUtils.h"
#import "CocoaUtils.h"
#import "ContactsManager.h"
#import "Validator.h"
#import <libextobjc/EXTScope.h>
#import "Utility.h"
#import "UserApi.h"
#import "CustomTextFieldView.h"
#import "Vars.h"
#import <PureLayout/PureLayout.h>
#import <YYKit/YYTimer.h>

@interface ResetPassWordViewController ()
@property (weak, nonatomic) IBOutlet CustomTextFieldView *emailView;
@property (weak, nonatomic) IBOutlet CustomTextFieldView *verificationView;
@property (weak, nonatomic) IBOutlet CustomTextFieldView *passwordView;
@property (weak, nonatomic) IBOutlet CustomTextFieldView *retypePasswordView;
@property (weak, nonatomic) IBOutlet UIButton *getVerificationCodeButton;
@property (weak, nonatomic) IBOutlet UIButton *submitButton;
@property (weak, nonatomic) IBOutlet UILabel *tipsLabel;

@property (nonatomic, strong) YYTimer *countDownTimer;
@property (nonatomic, assign) NSUInteger countDownNum;
@property(nonatomic, assign) BOOL isPause;
@property (nonatomic, strong, readonly) UITextField *emailField;
@property (nonatomic, strong, readonly) UITextField *verificationCodeField;
@property (nonatomic, strong, readonly) UITextField *passwordField;
@property (nonatomic, strong, readonly) UITextField *repasswordField;
@end

@implementation ResetPassWordViewController

- (instancetype)init {
	if (self = [super init]) {
		self.title = IMLocalizedString(@"Forgot Password");
		[[Vars appDelegate] applyDefaultConfigurationForViewController:self];
	}
	return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.countDownNum = 60;
    
    self.tipsLabel.text = IMLocalizedString(@"Forgot your password? Enter your email address for us to email you the instructions to reset your password.");
	
    self.emailField.placeholder = IMLocalizedString(@"Email Address");
    self.emailField.im_textContentType = IMTextContentTypeEmailAddress;
    self.emailField.autocapitalizationType = UITextAutocapitalizationTypeNone;
    self.emailField.autocorrectionType = UITextAutocorrectionTypeNo;
    self.emailField.keyboardType = UIKeyboardTypeEmailAddress;
    [CocoaUtils addKeyboardToolbarForTextField:self.emailField title:IMLocalizedString(@"Open Contacts") handler:^{
        [CocoaUtils showSelectionOfContactWithDisplayedPropertyKeys:@[CMContactEmailAddressesKey] completion:^(CMContactProperty *contactOrProperty) {
            self.emailField.text = contactOrProperty.value;
        }];
    }];
	
    self.verificationView.userInteractionEnabled = YES;
    self.verificationCodeField.placeholder =IMLocalizedString(@"Verification Code");
	self.verificationCodeField.clearsOnBeginEditing = YES;
    self.getVerificationCodeButton.backgroundColor =[Vars defaultTintColor];
	
    [self.getVerificationCodeButton setTitle:IMLocalizedString(@"Get Verification Code") forState:UIControlStateNormal];
	[Utility addRoundedBorderToButton:self.getVerificationCodeButton];
    self.passwordField.placeholder = IMLocalizedString(@"Password");
    self.passwordField.im_textContentType = IMTextContentTypePassword;
    self.passwordField.autocapitalizationType = UITextAutocapitalizationTypeNone;
    self.passwordField.autocorrectionType = UITextAutocorrectionTypeNo;
    self.passwordField.secureTextEntry = YES;
    self.passwordField.clearsOnBeginEditing = YES;
    
    self.repasswordField.placeholder = IMLocalizedString(@"Re-type Password");
    self.repasswordField.im_textContentType = IMTextContentTypePassword;
    self.repasswordField.autocapitalizationType = UITextAutocapitalizationTypeNone;
    self.repasswordField.autocorrectionType = UITextAutocorrectionTypeNo;
    self.repasswordField.secureTextEntry = YES;
    self.repasswordField.clearsOnBeginEditing = YES;
    
    [self.submitButton setTitle:IMLocalizedString(@"Reset Password") forState:UIControlStateNormal];
    self.submitButton.backgroundColor = [Vars defaultTintColor];
    [Utility addRoundedBorderToButton:self.submitButton];
}

#pragma mark - Property

-(YYTimer *)countDownTimer{
    if (!_countDownTimer) {
		_countDownTimer = [YYTimer timerWithTimeInterval:1 target:self selector:@selector(beginCountDown) repeats:YES];
		[[NSRunLoop mainRunLoop] addTimer:_countDownTimer forMode:NSRunLoopCommonModes];
    }
    return _countDownTimer;
}

- (UITextField *)emailField {
    return self.emailView.textField;
}

- (UITextField *)verificationCodeField{
    return self.verificationView.textField;
}

- (UITextField *)passwordField {
    return self.passwordView.textField;
}

- (UITextField *)repasswordField {
    return self.retypePasswordView.textField;
}

#pragma mark - Action

- (IBAction)sendEmail:(id)sender {
    if (![GenericValidator  isEmail:self.emailField.text]) {
        [CocoaUtils showAlertWithTitle:IMLocalizedString(@"Information") message:IMLocalizedString(@"Please enter the correct email address.")];
        return ;
    }
    
    ApplyResetPassword *resetPassword = [[ApplyResetPassword alloc] init];
    resetPassword.email = self.emailField.text;
    
    NSDictionary *requestDict = [BeanUtils describeAccessibleSimple:resetPassword];
	
    [Utility performRESTRequestWithMethod:@"POST" url:resetPassword.address parameters:requestDict success:^(id jsonObject) {
       ApplyResetPasswordResponse *response =  [Utility modelWithJSONObject:jsonObject withClass:[ApplyResetPasswordResponse class]];
		if (![StringUtils isEmpty:response.errorMessage]) {
			[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Error")  message:response.errorMessage];
		} else if(response.applyState == 1) {
            [CocoaUtils showAlertWithTitle:IMLocalizedString(@"Information") message:[NSString stringWithFormat:IMLocalizedString(@"We've sent a verifacetion code to the email %@. Please check and enter it to Verification Code."),self.emailField.text]];
            [self countdownVerificationCode];
        } else {
			[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Error")  message:[Vars responseException]];
        }
    }];
}

- (IBAction)resetPassWord:(id)sender {
    if (![self validatePassword]) {
        return ;
    }
    
    Reset *reset = [[Reset alloc] init];
    reset.email = self.emailField.text;
    reset.sid = self.verificationCodeField.text;
    reset.password = self.passwordField.text;
    reset.reTypePassword = self.repasswordField.text;
    
    NSDictionary *requesetDict = [BeanUtils describeAccessibleSimple:reset];
	
    [Utility performRESTRequestWithMethod:@"POST" url:reset.address parameters:requesetDict success:^(id jsonObject) {
        ResetResponse *response = [Utility modelWithJSONObject:jsonObject withClass:[ResetResponse class]];
		if (![StringUtils isEmpty:response.errorMessage]) {
			[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Error")  message:response.errorMessage];
		} else if (response.applyState == 1) {
            [CocoaUtils showAlertWithTitle:IMLocalizedString(@"Information") message:IMLocalizedString(@"Successfully modified") dismissalHandler:^{
                [self.navigationController popViewControllerAnimated:YES];
            }];
        } else {
			[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Error")  message:[Vars responseException]];
        }
    }];
}

#pragma mark - Private


-(BOOL)validatePassword{
    [self.scrollView endEditing:YES];
    for (UITextField *textField in @[self.emailField,self.passwordField, self.repasswordField,self.verificationCodeField]) {
        if ([StringUtils isBlank:textField.text]) {
            [CocoaUtils showAlertWithTitle:IMLocalizedString(@"Information") message:[NSString stringWithFormat:IMLocalizedString(@"Please fill out %@"), textField.placeholder.lowercaseString] dismissalHandler:^{
                [textField becomeFirstResponder];
            }];
            return NO;
        }
    }
    if (![self.passwordField.text isEqualToString:self.repasswordField.text]) {
        [CocoaUtils showAlertWithTitle:IMLocalizedString(@"Information") message:IMLocalizedString(@"Two passwords are not identical")];
        return NO;
    }
    return YES;
}

-(void)beginCountDown{
	if (!self.isPause) {
		[self.getVerificationCodeButton setTitle:[NSString stringWithFormat:@"%ld",self.countDownNum] forState:UIControlStateNormal];
		self.countDownNum--;
		if (self.countDownNum == 0 ) {
			self.countDownNum = 60;
			self.isPause = YES;
			self.getVerificationCodeButton.enabled = YES;
			[self.getVerificationCodeButton setTitleColor: [UIColor whiteColor] forState:UIControlStateNormal];
			self.getVerificationCodeButton.backgroundColor = [Vars  defaultTintColor];
			self.getVerificationCodeButton.layer.borderWidth = 0;
			[self.getVerificationCodeButton setTitle:IMLocalizedString(@"Get Verification Code") forState:UIControlStateNormal];
		}
	}
}

-(void)countdownVerificationCode{
    self.getVerificationCodeButton.backgroundColor = [UIColor whiteColor];
    [self.getVerificationCodeButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    self.getVerificationCodeButton.enabled = NO;
    self.getVerificationCodeButton.layer.borderColor = [UIColor lightGrayColor].CGColor;
    self.getVerificationCodeButton.layer.borderWidth = 1;
	self.isPause = NO;
    [self.countDownTimer fire];
}


@end
