//
//  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 "UserProfile.h"
#import <React/RCTLog.h>
#import "Rainbow/Rainbow.h"
#import "RNRainbowRn.h"
#import "IEventEmmiter.h"
#import "Contact+DictRepresentation.h"
#import "AuthenticationEventsNames.h"
#import "ContactsEventsNames.h"
#import <Rainbow/NSError+Details.h>
#import "MyUser+DictRepresentation.h"


@interface UserProfile ()
@property (nonatomic, strong) ContactsManagerService *contactsManagerService;
@property (nonatomic, strong) IEventEmmiter *eventEmitter;
@property (nonatomic, weak) RCTBridge *bridge;
@end

@implementation UserProfile
RCT_EXPORT_MODULE();

- (instancetype)init {
    self = [super init];
    if (self) {
        _contactsManagerService = [ServicesManager sharedInstance].contactsManagerService;
        [self registerConnectedUserEvents];
    }
    return self;
}

- (void)dealloc {
    [self unRegisterConnectedUserEvents];
}

#pragma mark - React Methode

RCT_EXPORT_METHOD(getConnectedUser) {
    NSLog(@"[%@] %@",[self class], NSStringFromSelector(_cmd));
    MyUser *myUser = [ServicesManager sharedInstance].myUser;
    if(myUser){
        [self sendEventWithName:CONNECTED_USER_UPDATED eventBody:myUser.myUserDictionaryRepresentation];
    }
}

RCT_EXPORT_METHOD(setPresence:(NSString *) presenceString) {
    Presence *presence = [self convertStringPrecenseToPrecenseObj:presenceString];
    [_contactsManagerService changeMyPresence:presence completionBlock:^(NSError *error) {
        if (error == nil) {
            NSLog(@"[UserProfile] %@ SUCCESS",NSStringFromSelector(_cmd));
            [self sendUserProfilePresenceDataChanges];
        } else {
            NSLog(@"[UserProfile] %@ Failed with error: %@",NSStringFromSelector(_cmd),error);
        }
    }];
}

RCT_EXPORT_METHOD(updateCustomData:(NSDictionary *) custumData) {
    NSLog(@"[UserProfile] %@ called",NSStringFromSelector(_cmd));
    [_contactsManagerService updateUserWithFields:@{@"customData" : custumData} withCompletionBlock:^(NSError *error) {
        if (error) {
            NSLog(@"[UserProfile] %@ Failed with Error: %@",NSStringFromSelector(_cmd),error);
        }
        else {
            NSLog(@"[UserProfile] %@ SUCCESS",NSStringFromSelector(_cmd));
        }
    }];
}

RCT_EXPORT_METHOD(updateUserPhoto:(NSString *) filePath) {
    NSLog(@"[%@] %@ called with image path: %@", [self class], NSStringFromSelector(_cmd), filePath);
    NSURL *url = [NSURL URLWithString:filePath];
    NSData *imageData = [[NSData alloc] initWithContentsOfURL:url];
    if (imageData) {
        UIImage *avatarImage = [UIImage imageWithData:imageData];
        NSMutableDictionary *fieldsDict = [NSMutableDictionary dictionary];
        [fieldsDict setObject:avatarImage forKey:@"photo"];
        [_contactsManagerService updateUserWithFields:fieldsDict withCompletionBlock:^(NSError *error) {
            if (error) {
                NSLog(@"[%@] %@ Failed with Error: %@", [self class], NSStringFromSelector(_cmd), error.description);
            }
            else {
                NSLog(@"[%@] %@ SUCCESS", [self class], NSStringFromSelector(_cmd));
            }
        }];
    }
   
}

RCT_EXPORT_METHOD(updateUserInfo:(NSDictionary *) updateUserRequest) {
    NSLog(@"[%@] %@ called with image path: %@", [self class], NSStringFromSelector(_cmd), updateUserRequest);
    [_contactsManagerService updateUserWithFields:[self getUpdatedUserFeild:updateUserRequest] withCompletionBlock:^(NSError *error) {
        if (error) {
            NSLog(@"[%@] %@ Failed with Error: %@", [self class], NSStringFromSelector(_cmd), error.description);
        }
        else {
            NSLog(@"[%@] %@ SUCCESS", [self class], NSStringFromSelector(_cmd));
        }
    }];
}

#pragma mark - UserProfile Methode

-(NSDictionary*) getUpdatedUserFeild:(NSDictionary*)updateUserRequest {
    NSMutableDictionary *userFeild = [[NSMutableDictionary alloc] init];
    if ([updateUserRequest valueForKeyPath:@"firstName"]) {
        NSString *firstName = [updateUserRequest valueForKeyPath:@"firstName"];
        [userFeild setValue:firstName forKey:@"firstname"];
    }
    if ([updateUserRequest valueForKeyPath:@"lastName"]) {
        NSString *lastName = [updateUserRequest valueForKeyPath:@"lastName"];
        [userFeild setValue:lastName forKey:@"lastname"];
    }
    if ([updateUserRequest valueForKeyPath:@"loginEmail"]) {
        NSString *loginEmail = [updateUserRequest valueForKeyPath:@"loginEmail"];
        [userFeild setValue:loginEmail forKey:@"personal_email"];
    }
    if ([updateUserRequest valueForKeyPath:@"nickName"]) {
        NSString *nickName = [updateUserRequest valueForKeyPath:@"nickName"];
        [userFeild setValue:nickName forKey:@"nickname"];
    }
    if ([updateUserRequest valueForKeyPath:@"title"]) {
        NSString *title = [updateUserRequest valueForKeyPath:@"title"];
        [userFeild setValue:title forKey:@"title"];
    }
    if ([updateUserRequest valueForKeyPath:@"jobTitle"]) {
        NSString *jobTitle = [updateUserRequest valueForKeyPath:@"jobTitle"];
        [userFeild setValue:jobTitle forKey:@"jobrole"];
    }
    if ([updateUserRequest valueForKeyPath:@"officePhone"]) {
        NSString *officePhone = [updateUserRequest valueForKeyPath:@"officePhone"];
        [userFeild setValue:officePhone forKey:@"professional_landphone"];
    }
    if ([updateUserRequest valueForKeyPath:@"mobilePhone"]) {
        NSString *mobilePhone = [updateUserRequest valueForKeyPath:@"mobilePhone"];
        [userFeild setValue:mobilePhone forKey:@"professional_mobilephone"];
    }
    if ([updateUserRequest valueForKeyPath:@"personalPhone"]) {
        NSString *personalPhone = [updateUserRequest valueForKeyPath:@"personalPhone"];
        [userFeild setValue:personalPhone forKey:@"personal_landphone"];
    }
    if ([updateUserRequest valueForKeyPath:@"personalMobilePhone"]) {
        NSString *personalMobilePhone = [updateUserRequest valueForKeyPath:@"personalMobilePhone"];
        [userFeild setValue:personalMobilePhone forKey:@"personal_mobilephone"];
    }
    if ([updateUserRequest valueForKeyPath:@"country"]) {
        NSString *country = [updateUserRequest valueForKeyPath:@"country"];
        [userFeild setValue:country forKey:@"country"];
    }
    if ([updateUserRequest valueForKeyPath:@"language"]) {
        NSString *language = [updateUserRequest valueForKeyPath:@"language"];
        [userFeild setValue:language forKey:@"language"];
    }
    if ([updateUserRequest valueForKeyPath:@"isInitialized"]) {
        NSString *isInitialized = [updateUserRequest valueForKeyPath:@"isInitialized"];
        [userFeild setValue:isInitialized forKey:@"isInitialized"];
    }
    if ([updateUserRequest valueForKeyPath:@"isGuest"]) {
        NSString *isGuest = [updateUserRequest valueForKeyPath:@"isGuest"];
        [userFeild setValue:isGuest forKey:@"forceGuestInitialize"];
    }
    if ([updateUserRequest valueForKeyPath:@"timeZone"]) {
        NSString *timeZone = [updateUserRequest valueForKeyPath:@"timeZone"];
        [userFeild setValue:timeZone forKey:@"timezone"];
    }
    if ([updateUserRequest valueForKeyPath:@"customData"]) {
        NSString *customData = [updateUserRequest valueForKeyPath:@"customData"];
        [userFeild setValue:customData forKey:@"customData"];
    }

    return userFeild;
}

- (Presence *)convertStringPrecenseToPrecenseObj:(NSString*) presence {
    if ([presence isEqual:@"online"]) {
        return Presence.presenceAvailable;
    }
    else if ([presence isEqual:@"away"]) {
        return Presence.presenceAway;
    }
    else if ([presence isEqual:@"DoNotDisturb"] || [presence isEqual:@"busy"]) {
        return Presence.presenceDoNotDisturb;
    }
    return Presence.presenceExtendedAway;
}

- (void) sendUserProfilePresenceDataChanges {
    MyUser *myUser = [ServicesManager sharedInstance].myUser;
    if (myUser) {
        NSLog(@"[%@] %@, with presence: %@",[self class],NSStringFromSelector(_cmd),myUser.contact.presence);
        [self sendEventWithName:CONNECTED_USER_UPDATED eventBody:myUser.myUserDictionaryRepresentation];
    }
}


#pragma mark - MyUser_Notifications

-(void)didUpdateMyContact:(NSNotification *) notification {
    //listen to my Contact Event Listener
    if(![NSThread isMainThread]){
        dispatch_async(dispatch_get_main_queue(), ^{
            [self didUpdateMyContact:notification];
        });
        return;
    }
    [self sendUserProfilePresenceDataChanges];
}

#pragma mark - Register SDK Event

-(void)registerConnectedUserEvents{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didUpdateMyContact:) name:kContactsManagerServiceDidUpdateMyContact object:nil];

}

-(void)unRegisterConnectedUserEvents{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kContactsManagerServiceDidUpdateMyContact object:nil];
}
- ( 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(@" [UserProfile] sendEventWithName: %@", eventName);
        [eventEmitter sendEvent:eventName eventBody:eventBody];
    } else {
        NSLog(@"[UserProfile] sendEventWithName:  Bridge is not ready. Cannot send event: %@", eventName);
    }
}
+ (BOOL)requiresMainQueueSetup
{
    return YES;
}
@end
