//
//  Search.m
//  rainbow
//
//  Created by Doha Tubaileh on 11/25/19.
//  Copyright © 2019 Facebook. All rights reserved.
//

#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#import <React/RCTBridgeModule.h>
#import "Search.h"
#import <React/RCTLog.h>
#import "Rainbow/Rainbow.h"
#import "IEventEmmiter.h"
#import "Contact+DictRepresentation.h"
#import "SearchEventsNames.h"
#import "Conversation+DictRepresentation.h"

#define SearchLimitPerCategory 20

@interface Search ()
@property (nonatomic, strong) ContactsManagerService *contactsManager;
@property (nonatomic, strong) MyUser *myUser;
@property (nonatomic, strong) NSMutableSet *searchResults;
@property (nonatomic, strong) IEventEmmiter *eventEmitter;
@property (nonatomic, weak) RCTBridge *bridge;
@end

@implementation Search

RCT_EXPORT_MODULE();
- (instancetype)init {
    self = [super init];
    if (self) {
        //do any init here
        _contactsManager = [ServicesManager sharedInstance].contactsManagerService;
        _myUser = [ServicesManager sharedInstance].myUser;
    }
    return self;
}

- (void)dealloc {
    _contactsManager = nil;
}

#pragma mark - React-native Methods


RCT_EXPORT_METHOD(searchContacts:(NSString*)query) {
    NSLog(@"[Search] searchContacts");
    [self performSearchWithSearchText:query];
}

#pragma mark - Others

-(void) performSearchWithSearchText:(NSString *) searchText {
    NSLog(@"[Search] performSearchWithSearchText");
    searchText = [searchText stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    
    if (searchText.length > 0) {
        _searchResults = [NSMutableSet new];
        //Seasrch in Conversation
        NSArray *conversations = [[ServicesManager sharedInstance].conversationsManagerService searchConversationWithPattern:searchText];
        if (conversations.count > 0) {
            //TODO: add the conversation to the search result
            //      for (Conversation *conversation in conversations) {
            //        NSDictionary *conversationDic = [conversation conversationDictionaryRepresentation];
            //        [_searchResults addObject:conversationDic];
            //      }
        }
        
        //Search in my contact
        NSArray<Contact *> *rosterContacts = [_contactsManager searchContactsWithPattern:searchText];
        if (rosterContacts.count > 0) {
            
            [self insertContacts:rosterContacts];
        }
        
        //Search into my address book
        NSArray<LocalContact *> *adressBook = [_contactsManager searchAddressBookWithPattern:searchText];
        if (adressBook.count > 0) {
            [self insertContacts:adressBook];
        }
    
        [self sendEventWithName:ContactsSearchResult eventBody:self->_searchResults.allObjects];
    }
}

-(void) insertContacts:(NSArray<Contact*> *)contacts{
    for (Contact *contact in contacts) {
        //ignore my self in the search result.
        if (contact == _myUser.contact) {
            continue;
        }
        NSDictionary *contactDic = [contact contactDictionaryRepresentation];
        [self->_searchResults addObject:contactDic];
    }
}
- ( 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(@" [Search] sendEventWithName: %@", eventName);
        [eventEmitter sendEvent:eventName eventBody:eventBody];
    } else {
        NSLog(@"[Search] sendEventWithName:  Bridge is not ready. Cannot send event: %@", eventName);
    }
}
+ (BOOL)requiresMainQueueSetup
{
    return NO;
}
@end
