//
//  Contact+DictRepresentation.m
//  rainbow
//
//  Created by Doha Tubaileh on 9/8/19.
//  Copyright © 2019 Facebook. All rights reserved.
//

#import "Rainbow/Rainbow.h"
#import "NSData+Base64String.h"
#import "NSString+PictureData.h"
#import "DefaultContactIcon.h"
#import "UIColor+ImageWithColorCreator.h"
#import "SearchGroupsTypes.h"
#import "unKnownContact.h"
#import "Contact+DictRepresentation.h"

#define KContactType @"Contact"

@implementation Contact (DictRepresentation)

- (NSDictionary *) getPresenceDictRepresentation {

     if (![self isKindOfClass:[RainbowContact class]]) {
        NSLog(@"Error: self is not a RainbowContact instance");
        return @{};
    }
    NSLog(@"[Contact+DictRepresentation] getPresenceDictRepresentation");
    NSMutableDictionary *newPresence = [[NSMutableDictionary alloc]init];
    NSString *contactPresence = [self presenceConverterForReact];
    [newPresence setValue:[(RainbowContact*)self jid] forKey:@"contactJId"];
    [newPresence setValue:contactPresence forKey:@"presence"];
    return newPresence;
}

- (NSDictionary *) contactDictionaryRepresentation {

    NSLog(@"[Contact+DictRepresentation] contactDictionaryRepresentation");
    NSMutableDictionary *contactObject = [[NSMutableDictionary alloc]init];
    NSString *contactName = self.fullName;
    NSString *firstAvailableNumber = nil;

    for (PhoneNumber *phoneNumber in self.phoneNumbers) {
        firstAvailableNumber = phoneNumber.number;
        break;
    }
    MyUser *myUser = [ServicesManager sharedInstance].myUser;
    BOOL isMyUser = false;

    if ([self photoData] != nil) {
        NSString *serverName = [ServicesManager.sharedInstance myUser].server.serverDisplayedName;
        NSString *imageURL = [NSString stringWithFormat:@"https://%@/api/avatar/%@?size=256",serverName, [(RainbowContact*)self rainbowID]];
        [contactObject setValue:imageURL forKey:@"imageURL"];
    }
    else if (self.fullName != nil || self.fullName.length) {
        NSString *firstChar = [self.firstName substringToIndex:1];
        NSString *secondChar = [self.lastName substringToIndex:1];
        NSString *nameInitials = [NSString stringWithFormat:@"%@ %@",firstChar,secondChar];
        [contactObject setValue:nameInitials forKey:@"nameInitials"];
    }
    else {
        //Incase there is no name like PBX Contacts
        //make there name are phone number
        contactName = firstAvailableNumber;
        //set this contact image blank color
        [contactObject setValue:@"??" forKey:@"nameInitials"];
    }
    if ([self isKindOfClass:[RainbowContact class]]) {
        RainbowContact *rainbowContact = (RainbowContact *)self;
        [contactObject setValue:[NSNumber numberWithBool:[rainbowContact isInRoster]] forKey:@"isRoster"];
        [contactObject setValue:[NSNumber numberWithBool:YES] forKey:@"isRainbowUser"];
        [contactObject setValue:[rainbowContact jid] forKey:@"jId"];
        [contactObject setValue:[rainbowContact presenceConverterForReact] forKey:@"presence"];
        isMyUser =  [[rainbowContact jid] isEqual:myUser.contact.jid];

    } 
    if ([self isKindOfClass:[ExternalContact class]]){
        ExternalContact *externalContact = (ExternalContact *)self;
//        [contactObject setValue:[NSNumber numberWithBool:externalContact.isDirectoryContact] forKey:@"isCompanyDirectoryContact"];
//        [contactObject setValue:[NSNumber numberWithBool:[self isPBXContact]] forKey:@"isPhoneBook"];
    }
    if ([self isKindOfClass:[LocalContact class]]){

    }
    [contactObject setValue:contactName forKey:@"name"];
    [contactObject setValue:[self getEmailsMap:self] forKey:@"emails"];
    [contactObject setValue:[self getPhoneNumbersMap:self] forKey:@"phoneNumbers"];
    [contactObject setValue:[NSNumber numberWithBool:(self.sentInvitationId != nil)] forKey:@"isInvited"];
    [contactObject setValue:[self jobTitle]==nil?@"":[self jobTitle] forKey:@"jobTitle"];
    [contactObject setValue:[self companyName]==nil?@"":[self companyName] forKey:@"companyName"];
    [contactObject setValue:[self companyId]==nil?@"":[self companyId] forKey:@"companyId"];

    [contactObject setValue:firstAvailableNumber forKey:@"firstAvailableNumber"];
    [contactObject setValue:[NSNumber numberWithBool:isMyUser] forKey:@"isMyUser"];
    [contactObject setValue:KContactType forKey:@"type"];
    [contactObject setValue:[NSNumber numberWithBool:NO] forKey:@"isLocalPhoneContact"];
    
    //TODO: add isCorpotate,isOffice365,First availabe number
    return contactObject;
}

- (NSArray *) getEmailsMap:(Contact*)contact {
    NSLog(@"[Contact+DictRepresentation] getEmailsMap for %@",contact.fullName);
    NSMutableArray *emailsArray = [[NSMutableArray alloc]init];
    NSArray<EmailAddress*> *emailsAddresses = [contact emailAddresses];
    for (EmailAddress *email in emailsAddresses) {
        NSMutableDictionary *emailDic = [[NSMutableDictionary alloc]init];
        [emailDic setValue:[self mailConverterForReact:email] forKey:@"type"];
        [emailDic setValue:[email address] forKey:@"value"];
        [emailsArray addObject:emailDic];
    }
    return emailsArray;
}

- (NSArray *)getPhoneNumbersMap:(Contact*)contact {
    NSLog(@"[Contact+DictRepresentation] getPhoneNumbersMap for %@",contact.fullName);
    NSMutableArray *phoneNumArray = [[NSMutableArray alloc]init];
    NSSet<PhoneNumber *> *phoneNumbers = [contact phoneNumbers];
    for (PhoneNumber *phone in phoneNumbers) {
        NSMutableDictionary *phoneDic = [[NSMutableDictionary alloc]init];
        [phoneDic setValue:[self phoneConverterForReact:phone] forKey:@"type"];
        if (phone.numberE164 == nil) {
            //the extension number DONOT have numberE164, also for my GSM contacts
            [phoneDic setValue:[phone number] forKey:@"value"];
        }
        else {
            [phoneDic setValue:[phone numberE164] forKey:@"value"];
        }
        [phoneNumArray addObject:phoneDic];
    }

    return phoneNumArray;
}

- (NSString *)presenceConverterForReact {
    RainbowContact *rainbowContact = (RainbowContact*)self;
    if (![self isKindOfClass:[RainbowContact class]]) {
        NSLog(@"Error: self is not a RainbowContact instance");
        return @"offline";
    }

    if (rainbowContact.isConnectedWithMobile && rainbowContact.presence.presence == ContactPresenceAvailable) {
        return @"mobile_online";
    }
    switch (rainbowContact.presence.presence) {
        case ContactPresenceAvailable:
            return @"online";
        case ContactPresenceDoNotDisturb:
            return @"DoNotDisturb";
        case ContactPresenceBusy:
            return @"busy";
        case ContactPresenceAway:
            return @"away";
        default:
            return @"offline";
    }

}

- (NSString *)mailConverterForReact:(EmailAddress*)mail {

    switch ([mail type]) {
        case EmailAddressTypeHome:
            return @"HOME";
        case EmailAddressTypeWork:
            return @"WORK";
        default:
            return @"OTHER";
    }

}

- (NSString *)phoneConverterForReact:(PhoneNumber*)phone {

    if (phone.deviceType == PhoneNumberDeviceTypeMobile) {
        switch (phone.type) {
            case PhoneNumberTypeHome://Personal Mobile
                return @"MOBILE";
                break;

            case PhoneNumberTypeWork://Professional Mobile
                return @"WORK_MOBILE";
                break;

            case PhoneNumberTypeOther://Professional Mobile
                return @"WORK_MOBILE";
                break;
            default://Cell
                return @"MAIN";
                break;
        }
    }
    else {//PhoneNumberDeviceTypeLandline
        switch (phone.type) {
            case PhoneNumberTypeHome://Personal
                return @"HOME";
                break;

            case PhoneNumberTypeWork://Extension number or Professional
                return phone.isInternal ? @"WORK" : @"COMPANY_MAIN";
                break;

            default://Work
                return @"OFFICE";
                break;
        }
    }
}

- (UIImage *) getContactImage {
    if (self.photoData == nil) {
        // In case this contact has no name or nil name send blank gray color image
        if (self.fullName == nil || !self.fullName.length) {
            return [UIColor.lightGrayColor imageFromColor];
        }
        else {
            return [[UIImage alloc] initWithData:[self.fullName getImageData]];
        }

    }

    else {
        return [[UIImage alloc] initWithData:self.photoData];
    }

}

-(NSString *) getContacType {
    NSString *myUserCompanyId = [ServicesManager sharedInstance].myUser.contact.companyId;

    if ([self isKindOfClass:[RainbowContact class]]) {
             RainbowContact *rainbowContact = (RainbowContact *)self;
        if(rainbowContact.isInRoster) {
            //MyNetwork
            return kSearchResultKeyMyNetwork;
        } else if ([myUserCompanyId isEqualToString:self.companyId]) {
            //MyCompany
            return kSearchResultKeyMyCompany;
        } else {
            return kSearchResultKeyContactsOfOtherCompanies;
        }

    } else if ([self isKindOfClass:[ExternalContact class]]){
        return kSearchResultKeyOtherDirectoriesOfMyCompany;
    } else{
        return kSearchResultKeyPhoneContacts;

    }
}

@end

