//
//  APMUIServicesUserModule.m
//  RCTAPMBanner
//
//  Created by Vincent Ducastel on 09/08/2017.
//  Copyright © 2017 Facebook. All rights reserved.
//

#import "APMUIServicesUserModule.h"
#import "APMBridgeUtils.h"

#import <React/RCTLog.h>
#import <React/RCTConvert.h>
#import <APMBanner/APMHeaders.h>

@implementation APMUIServicesUserModule

RCT_EXPORT_MODULE();

- (dispatch_queue_t)methodQueue
{
    return dispatch_get_main_queue();
}

RCT_EXPORT_METHOD(userClientConnect:(NSString*)firstname lastname:(NSString*)lastname email:(NSString*)email password:(NSString*)password facebookId:(NSString*)facebookId partnerClientId:(NSString*)partnerClientId oldClientId:(NSString*)oldClientId segments:(NSDictionary*)segments resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
{
    @try
    {
        [APMUIServicesUser userClientConnect:firstname lastname:lastname email:email password:password facebookId:facebookId partnerClientId:partnerClientId oldClientId:oldClientId segments:segments userConnectSuccess:^(APMUser *user) {
            NSLog(@"user : %@", user);
            resolve([user getUserDictionary]);
        } failure:^(NSError *error) {
            
            NSLog(@"error : %@", error);
            reject([NSString stringWithFormat:@"%li", (long)error.code], error.localizedDescription, error);
        }];
    }
    @catch (NSException *exception)
    {
        NSError* error = [APMBridgeUtils errorFromException:exception];
        reject([NSString stringWithFormat:@"%li", (long)error.code], error.localizedDescription, error);
    }
}

RCT_EXPORT_METHOD(userLogout:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
{
    @try
    {
        [APMUIServicesUser userLogout:^{
            resolve(nil);
        } failure:^(NSError *error) {
            NSLog(@"error : %@", error);
            reject([NSString stringWithFormat:@"%li", (long)error.code], error.localizedDescription, error);
        }];
    }
    @catch (NSException *exception)
    {
        NSError* error = [APMBridgeUtils errorFromException:exception];
        reject([NSString stringWithFormat:@"%li", (long)error.code], error.localizedDescription, error);
    }
}

@end
