#import "RCTIREventEmitter.h"
#import "RNInvitereferrals.h"
#import <UIKit/UIKit.h>

static BOOL hasListeners;

BOOL wasDelegateSet = NO;

RCTResponseSenderBlock callbackCB;

@implementation RCTIREventEmitter{
  BOOL hasListeners;
}

@synthesize irName, irEmail, irMobile, irCampaignID;

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

static BOOL _startObserving = false;

+ (BOOL)hasSetBridge {
    return _startObserving;
}

+(BOOL)requiresMainQueueSetup {
    return YES;
}

RCT_EXPORT_MODULE(RNInvitereferrals);
//RCT_EXPORT_MODULE();

#pragma mark RCTEventEmitter Subclass Methods

-(instancetype)init {
    if (self = [super init]) {
        NSLog(@"init method was called");
        for (NSString *eventName in [self supportedEvents])
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(emitEvent:) name:eventName object:nil];
    }
    return self;
}

- (NSArray<NSString *> *)supportedEvents {
    return @[@"ir_close_button_click", @"ir_tracking_event"];
}

// Will be called when this module's first listener is added.
- (void)startObserving {
    hasListeners = YES;
    NSLog(@"startObserving method was called");
    [[NSNotificationCenter defaultCenter] postNotificationName:@"didSetBridge" object:nil];
    _startObserving = true;
}

// Will be called when this module's last listener is removed, or on dealloc.
- (void)stopObserving {
     NSLog(@"stopObserving method was called");
     hasListeners = NO;
}

// Send Event Methods
- (void)emitEvent:(NSNotification *)notification {
    if (!hasListeners) {
        NSLog(@"Attempted to send an event. When no listeners were set");
        return;
    }
    [self sendEventWithName:notification.name body:notification.userInfo];
}

+ (void)sendEventWithName:(NSString *)name withBody:(NSDictionary *)body {
    if (hasListeners) {
        NSLog(@"sendEventWithName method was called");
        [[NSNotificationCenter defaultCenter] postNotificationName:name object:nil userInfo:body];
    }
}

/* user details */
RCT_EXPORT_METHOD(userDetails:(NSString*_Nullable)name  email:(NSString*_Nullable)email mobile:(NSString*_Nullable)mobile
                  campaignID:(NSString*_Nullable)campaignID customValue:(NSString*_Nullable)customValue
                  SubscriptionID:(NSString *_Nullable)subscriptionID callback:(RCTResponseSenderBlock)callback) {
    @try{
        NSLog(@"USER DETAILS !!");
        // these varibales will required in tracking method
        self.irName = name;
        self.irEmail = email;
        self.irMobile = mobile;
        self.irCampaignID = campaignID;
        
        [InviteReferrals GetShareDataWithCampaignID: self.irCampaignID Email: self.irEmail mobile: self.irMobile name: self.irName SubscriptionID: subscriptionID ShowErrorAlerts: YES ShowActivityIndicatorViewWhileLoading: NO SharingDetails:^(NSMutableDictionary *irDetails) {
            callback(@[@"success", [NSNull null]]);
        }];
    }
    @catch(NSException *exception){
        callback(@[exception.reason, [NSNull null]]);
        NSLog(@"%@", exception.reason);
    }
}

/* get sharing details */
RCT_EXPORT_METHOD(getSharingDetails:(NSString*_Nullable)name  email:(NSString*_Nullable)email mobile:(NSString*_Nullable)mobile
                  campaignID:(NSString*_Nullable)campaignID callback:(RCTResponseSenderBlock)callback) {
    @try{
        NSLog(@"GET SHARING DETAILS !!");
        
        if ([self.irName  isEqual: [NSNull null]]) {
            name = self.irName ;
        }
        if ([self.irEmail isEqual: [NSNull null]]) {
            email = self.irEmail;
        }
        if ([self.irMobile isEqual: [NSNull null]]) {
           mobile= self.irMobile;
        }
        if ([campaignID isEqual: [NSNull null]]) {
            campaignID = self.irCampaignID;
        }
    
        [InviteReferrals GetShareDataWithCampaignID: campaignID Email: email mobile: mobile name: name SubscriptionID: nil ShowErrorAlerts: YES ShowActivityIndicatorViewWhileLoading: NO SharingDetails:^(NSMutableDictionary *irDetails) {
            
            if([irDetails count] > 0){
                NSError *nvError = nil;
                NSData *nvJsonData = [NSJSONSerialization dataWithJSONObject: irDetails options:NSJSONWritingPrettyPrinted error: &nvError];
                NSString *nvJsonString = [[NSString alloc] initWithData: nvJsonData encoding: NSUTF8StringEncoding];
                callback(@[nvJsonString, [NSNull null]]);
            }else{
                callback(@[@"No Data Found !! ", [NSNull null]]);
            }
    
        }];
    }
    @catch(NSException *exception){
        callback(@[exception.reason, [NSNull null]]);
        NSLog(@"%@", exception.reason);
    }
}



/* login & sharing screen */
RCT_EXPORT_METHOD(inline_btn:(NSString*_Nullable)campaignID){
    @try{
        NSLog(@"INLINE BUTTON !!");
        [InviteReferrals launch: campaignID Email: nil mobile: nil name: nil SubscriptionID: nil];
    }
    @catch(NSException *exception){
        NSLog(@"%@", exception.reason);
    }
}

/* show login pop up alert */
RCT_EXPORT_METHOD(invite:(NSString*_Nullable)irPopupRule){
    @try{
        NSLog(@"INVITE !!");
        [InviteReferrals showSharePopup: irPopupRule Email: nil mobile: nil name: nil SubscriptionID: nil];
    }
    @catch(NSException *exception){
        NSLog(@"%@", exception.reason);
    }
}


/* for first time to show welcome message */
RCT_EXPORT_METHOD(showWelcomeMessage){
    @try{
        NSLog(@"SHOW WELCOME MESSAGE !!");
        [InviteReferrals welcomeMessage];
    }
    @catch(NSException *exception){
        NSLog(@"%@", exception.reason);
    }
}

/* install , sale & register tracking */
RCT_EXPORT_METHOD(tracking:(NSString*_Nullable)irEvent orderID:(NSString*_Nullable)irOrderID
                  purchaseValue:(NSString*_Nullable)irPurchaseValue referCode:(NSString *_Nullable)irReferCode
                  uniqueCode:(NSString *_Nullable)irUniqueCode){
    @try{
         NSLog(@"TRACKING !!");
         [self setIRDelegate];
         [InviteReferrals tracking: irEvent orderID: irOrderID purchaseValue: irPurchaseValue email: irEmail mobile: irMobile name: irName referCode: irReferCode uniqueCode: irUniqueCode isDebugMode: NO ComplitionHandler:^(NSMutableDictionary *irTrackingResponse) {
             // callback is sending by event
        }];
    }
    @catch(NSException *exception){
        NSLog(@"%@", exception.reason);
    }
}


/* for getting referrer code */
RCT_EXPORT_METHOD(getReferrerCode: (RCTResponseSenderBlock)callback){
    @try{
        NSLog(@"GET REFERRER CODE !!");
        [InviteReferrals getReferrerCode:^(NSString * referrerCode) {
            if([referrerCode length] > 0 ){
                callback(@[referrerCode, [NSNull null]]);
            }else{
                callback(@[@"null", [NSNull null]]);
            }
        }];
    }
    @catch(NSException *exception){
        NSLog(@"%@", exception.reason);
    }
}

/* set language */
RCT_EXPORT_METHOD(setLocale: (NSString*_Nullable)languageCode){
    @try{
        NSLog(@"SET LOCALE !!");
        [InviteReferrals setLocalizationLanguage:languageCode];
    } @catch(NSException *exception){
        NSLog(@"%@", exception.reason);
    }
}

/* Refererr Parameters */
RCT_EXPORT_METHOD(getReferringParams:(RCTResponseSenderBlock)callback){
    @try{
        NSLog(@"GET REFERRING PARAMS !!");
        [InviteReferrals getReferringParams:^(NSDictionary * irRefParams) {
            if([irRefParams count] > 0 ){
                NSError * irErr;
                NSData * irResponseJsonData = [NSJSONSerialization dataWithJSONObject: irRefParams options: 0 error: &irErr];
                NSString * irResponseStr = [[NSString alloc] initWithData: irResponseJsonData encoding: NSUTF8StringEncoding];
                callback(@[irResponseStr, [NSNull null]]);
            } else{
                callback(@[@"null", [NSNull null]]);
            }
        }];
    }
    @catch(NSException *exception){
        NSLog(@"%@", exception.reason);
    }
}



/* Close Button callback event */
RCT_EXPORT_METHOD(closeButtonListener){
    @try{
        NSLog(@"CLOSE BUTTON LISTENER !!");
        [self setIRDelegate];
    }
    @catch(NSException *exception){
        NSLog(@"%@", exception.reason);
    }
}


/* Close Button callback event */
-(void)HandleDoneButtonActionWithUserInfo:(NSMutableDictionary *)userInfo{
    @try {
           NSLog(@"CLOSE BUTTON LISTENER !!");
           [self sendEventWithName:@"ir_close_button_click" body:@{@"data":@"success"}];
     }@catch(NSException *exception){
        NSLog(@"%@", exception.reason);
    }
}


/* tracking callback event */
-(void)InviteReferralsTrackingFinishedforEventname:(NSString *)eventName withResponse:(NSMutableDictionary *)trackingResponse{
    @try {
        NSLog(@"INVITEREFERRS TRACKING FINISHED FOR EVENT NAME  !!");
        NSError * irErr;
        NSData * irResponseJsonData = [NSJSONSerialization dataWithJSONObject: trackingResponse options: 0 error: &irErr];
        NSString * irResponseStr = [[NSString alloc] initWithData: irResponseJsonData encoding: NSUTF8StringEncoding];
        [self sendEventWithName:@"ir_tracking_event" body:@{@"data":irResponseStr}];
    
    }@catch(NSException *exception){
        NSLog(@"%@", exception.reason);
    }
}

/* set Inviteferrals Delegate */
-(void)setIRDelegate{
    @try {
         NSLog(@"SET IR DELEGATE!!");
        if(!wasDelegateSet){
            [InviteReferrals sharedInstance].delegate = self;
            wasDelegateSet = YES;
        } else{
            NSLog(@"IR DELEGATE ALLREADY SET !!");
        }
    }@catch(NSException *exception){
        NSLog(@"%@", exception.reason);
    }
    
}

@end

//            NSError * irErr;
//            NSData * irResponseJsonData = [NSJSONSerialization dataWithJSONObject: irTrackingResponse options: 0 error: &irErr];
//            NSString * irResponseStr = [[NSString alloc] initWithData: irResponseJsonData encoding: NSUTF8StringEncoding];
//            [self sendEventWithName:@"ir_tracking_event" body:@{@"data":irResponseStr}];
//            callback(@[[NSNull null], irResponseStr]);

//          [InviteReferrals setupUserID:email mobile:mobile name:name gender:nil
//          shareLink:nil shareTitle:nil shareDesc:nil shareImg:nil customValue:customValue
//          campaignID:campaignID flag:nil SubscriptionID: subscriptionID];

//          callback(@[exception.reason, [NSNull null]]);

//           if(userInfo != NULL && userInfo != nil){
//               NSError *irError = nil;
//               NSData *irJsonData = [NSJSONSerialization dataWithJSONObject: userInfo options: NSJSONWritingPrettyPrinted error: &irError];
//               NSString *irJsonString = [[NSString alloc] initWithData: irJsonData encoding: NSUTF8StringEncoding];
//               [self sendEventWithName:@"ir_close_button_click" body:@{@"data":@"success"}];
//        } else{
//            [self sendEventWithName:@"ir_close_button_click" body:@{@"data":@"null"}];
//        }
