#import "TrimsyContacts.h"

@implementation TrimsyContacts

- (void)list:(CDVInvokedUrlCommand *)command {
    CNContactStore *store = [[CNContactStore alloc] init];
    [store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError *error) {
        if (!granted) {
            CDVPluginResult *denied = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"denied"];
            [self.commandDelegate sendPluginResult:denied callbackId:command.callbackId];
            return;
        }
        [self.commandDelegate runInBackground:^{
            NSMutableArray *out = [NSMutableArray array];
            NSArray *keys = @[
                CNContactIdentifierKey,
                CNContactGivenNameKey,
                CNContactFamilyNameKey,
                CNContactOrganizationNameKey,
                CNContactPhoneNumbersKey
            ];
            CNContactFetchRequest *req = [[CNContactFetchRequest alloc] initWithKeysToFetch:keys];
            req.sortOrder = CNContactSortOrderGivenName;
            NSError *fetchError = nil;
            [store enumerateContactsWithFetchRequest:req error:&fetchError usingBlock:^(CNContact *contact, BOOL *stop) {
                NSString *given = contact.givenName ?: @"";
                NSString *family = contact.familyName ?: @"";
                NSString *name = [[NSString stringWithFormat:@"%@ %@", given, family]
                                  stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
                if (name.length == 0) name = contact.organizationName ?: @"";
                NSString *phone = @"";
                if (contact.phoneNumbers.count > 0) {
                    phone = contact.phoneNumbers.firstObject.value.stringValue ?: @"";
                }
                if (name.length == 0 && phone.length == 0) return;
                [out addObject:@{
                    @"id": contact.identifier ?: @"",
                    @"name": name,
                    @"phone": phone
                }];
            }];
            if (fetchError) {
                CDVPluginResult *fail = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR
                                                         messageAsString:(fetchError.localizedDescription ?: @"read_failed")];
                [self.commandDelegate sendPluginResult:fail callbackId:command.callbackId];
                return;
            }
            CDVPluginResult *ok = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArray:out];
            [self.commandDelegate sendPluginResult:ok callbackId:command.callbackId];
        }];
    }];
}

@end
