//
//  ForgotPassword.m
//  rainbow
//
//  Created by Doha Tubaileh on 6/25/20.
//  Copyright © 2020 Facebook. All rights reserved.
//

#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#import <React/RCTBridgeModule.h>
#import "ForgotPassword.h"
#import <React/RCTLog.h>
#import "Rainbow/Rainbow.h"
#import "RNRainbowRn.h"
#import "IEventEmmiter.h"
#import "Contact+DictRepresentation.h"
#import "AuthenticationEventsNames.h"
#import <Rainbow/NSError+Details.h>


@interface ForgotPassword ()
@property (strong, nonatomic) IEventEmmiter *eventEmitter;
@property (nonatomic, weak) RCTBridge *bridge;

@end

@implementation ForgotPassword

RCT_EXPORT_MODULE();

- (instancetype)init {
    self = [super init];
    if (self) {
    }
    return self;
}

- (void)dealloc {
    
}

#pragma mark - ReactNative_functions

RCT_EXPORT_METHOD(sendForgetPasswordEmail:(NSString*) email) {
    
    NSLog(@"[ForgotPassword] sendForgetPassword with email: %@", email);
    [[ServicesManager sharedInstance].loginManager sendResetPasswordEmailWithLoginEmail:email completionHandler:^(NSDictionary *jsonResponse, NSError *error) {
        if(error){
            NSLog(@"[ForgotPassword] sendForgetPassword Failure with error msg: %@", error.localizedDescription);
            
            [self sendEventWithName:ForgetPswEmailResult eventBody:GenericError];
        }
        else {
            // Everything ok
            NSLog(@"[ForgotPassword] sendForgetPassword success");
            [self sendEventWithName:ForgetPswEmailResult eventBody:NSNull.null];
            [[ServicesManager sharedInstance].loginManager setUsername:email andPassword:nil];
        }
    }];
}

RCT_EXPORT_METHOD(resetPassword:(NSString *)verificationCode newPassword:(NSString *)newPassword) {
    
    NSString *emailEntered = [ServicesManager sharedInstance].myUser.username;
    NSLog(@"[ForgotPassword] resetPassword with email: %@",emailEntered);
    [[ServicesManager sharedInstance].loginManager sendResetPasswordWithLoginEmail:emailEntered password:newPassword temporaryCode:verificationCode completionHandler:^(NSDictionary *jsonResponse, NSError *error) {
        
        if(error){
            NSLog(@"[ForgotPassword] resetPassword failed with error mag: %@",error.localizedDescription);
            if (jsonResponse) {
                NSNumber *errorCode = (NSNumber*)jsonResponse[@"errorCode"];
                if(errorCode.integerValue == 400){
                    // Check if the error is regarding token length
                    BOOL tokenLengthError = NO;
                    NSArray *errorDetails = jsonResponse[@"errorDetails"];
                    for (NSDictionary *errorDetail in errorDetails) {
                        if([errorDetail[@"param"] isEqualToString:@"temporaryToken"]){
                            tokenLengthError = YES;
                            break;
                        }
                    }
                    
                    if(tokenLengthError){
                        NSLog(@"[ForgotPassword] resetPassword Token length invalid");
                        [self sendEventWithName:ResetPswResult eventBody:NoValidToken];

                    } else {
                        NSLog(@"[ForgotPassword] resetPassword Invalid password, Password must be more than 8 characters...");
                        [self sendEventWithName:ResetPswResult eventBody:PasswordViolation];
                    }
                }
                else if(errorCode.integerValue == 401 || errorCode.integerValue == 403 || errorCode.integerValue == 404 || errorCode.integerValue == 409 ) {
                    NSNumber *detailedCode = (NSNumber *)jsonResponse[@"errorDetailsCode"];
                    if(detailedCode.integerValue == 401600){
                        [self sendEventWithName:ResetPswResult eventBody:NoValidToken];
                    }
                    else{
                        [self sendEventWithName:ResetPswResult eventBody:ForbiddenAccount];
                    }
                }
                else {
                    [self sendEventWithName:ResetPswResult eventBody:GenericError];
                }
            }
            
        } else {
            //on Success
            NSLog(@"[ForgotPassword] resetPassword Success");
            [self sendEventWithName:ResetPswResult eventBody:NSNull.null];
            // Everything ok, saving given username and password
            [[ServicesManager sharedInstance].loginManager setUsername:emailEntered andPassword:newPassword];
            [[ServicesManager sharedInstance].loginManager connect];
            // This will trigger didLogin notification and it will login directly
        }
        
    }];
    
}

- ( IEventEmmiter *)eventEmitter {
    if (!_eventEmitter) {
        _eventEmitter = [self.bridge moduleForClass:[IEventEmmiter class]];
    }
    return _eventEmitter;
}

- (void)sendEventWithName:(NSString *)eventName eventBody:(id)eventBody {
    IEventEmmiter *eventEmitter = [self eventEmitter];
    if (eventEmitter) {
        NSLog(@" [ForgotPassword] sendEventWithName: %@", eventName);
        [eventEmitter sendEvent:eventName eventBody:eventBody];
    } else {
        NSLog(@"[ForgotPassword] sendEventWithName:  Bridge is not ready. Cannot send event: %@", eventName);
    }
}
+ (BOOL)requiresMainQueueSetup
{
    return NO;
}
@end
