//
//  CallLogHelper.m
//  rainbow
//
//  Created by Doha Tubaileh on 9/24/19.
//  Copyright © 2019 Facebook. All rights reserved.
//

#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#import <React/RCTBridgeModule.h>
#import <React/RCTLog.h>
#import "Rainbow/Rainbow.h"
#import <WebRTC/WebRTC.h>
#import "CallLogHelper.h"
#import "Contact+DictRepresentation.h"
#import "NSDate+ReactDateFormatter.h"
#import "CallLog+CallStateToReactConverter.h"


@interface CallLogHelper ()

@end

@implementation CallLogHelper

+(id)sharedManager {
    static CallLogHelper *sharedMyManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedMyManager = [[self alloc] init];
    });
    return sharedMyManager;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        //do any init here
    }
    return self;
}
- (void)dealloc {
    
}

-(NSArray*)processCallLogs:(NSArray <CallLog*> *) callLogs {
    NSLog(@"[CallLogHelper] processCallLogs");
    //gets all uniques contacts object in call logs array
    NSArray *peers = [callLogs valueForKey:@"remoteParty"];
    NSArray *uniquePeers = [[NSSet setWithArray:peers] allObjects];
    NSMutableArray *callLogsArray = [[NSMutableArray alloc] init];
    for (Contact *contact in uniquePeers) {
        Contact *callContact = (Contact*)contact;
        NSMutableDictionary *callLogDic = [[NSMutableDictionary alloc] init];
        [callLogDic setValue:callContact.contactDictionaryRepresentation forKey:@"contact"];
        
        //now get all call logs for the contact
        NSMutableArray<CallLog*> *contactCallLogs = [[NSMutableArray alloc]init];
        for (CallLog *callLog in callLogs) {
            if (callLog.remoteParty == contact) {
                [contactCallLogs addObject:callLog];
            }
        }
        //sort call history array for this contact
        [contactCallLogs sortUsingComparator:^NSComparisonResult(CallLog *obj1, CallLog *obj2) {
            return [obj2.date compare:obj1.date];
        }];
        //get last call
        CallLog *lastCallLog = contactCallLogs[0];
        NSMutableDictionary *lastCallLogDic = [[NSMutableDictionary alloc] init];
        [lastCallLogDic setValue:lastCallLog.date.changeDateFormatToReact forKey:@"date"];
        [lastCallLogDic setValue:lastCallLog.callStateConverterForReact forKey:@"state"];
        [callLogDic setValue:lastCallLogDic forKey:@"lastCall"];
        NSMutableArray *contactCallHistory = [[NSMutableArray alloc] init];
        //get all call logs in
        for (CallLog *log in contactCallLogs) {
            NSMutableDictionary *call = [[NSMutableDictionary alloc] init];
            if (log.state == CallLogStateAnswered) {
                
                [call setValue:[self durationConverter:log.duration] forKey:@"duration"];
            }
            [call setValue:log.callStateConverterForReact forKey:@"state"];
            [call setValue:log.date.changeDateFormatToReact forKey:@"date"];
            [contactCallHistory addObject:call];
        }
        [callLogDic setValue:contactCallHistory forKey:@"callsList"];
        [callLogsArray addObject:callLogDic];
    }
    //sort the call log array ,each contact to its last call date
    callLogsArray = [callLogsArray sortedArrayUsingComparator:^NSComparisonResult(NSDictionary *p1, NSDictionary *p2) {
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"EEE MMM dd hh:mm:ss yyyy"];
        NSDate *d1 = [dateFormatter dateFromString:p1[@"lastCall"][@"date"]];
        NSDate *d2 = [dateFormatter dateFromString:p2[@"lastCall"][@"date"]];
        return [d2 compare: d1];
    }].mutableCopy;
    return callLogsArray;
}

-(NSString*)durationConverter:(NSString *)duration {
    //convert from counting second only to sec, min and hr
    if (duration != nil) {
        NSString *durationString = @"";
        NSInteger timeInSeconds = [duration integerValue];
        int seconds = timeInSeconds % 60;
        int minutes = (timeInSeconds / 60) % 60;
        long hours = timeInSeconds / 3600;
        durationString = hours > 0 ? [durationString stringByAppendingString:[NSString stringWithFormat:@"%02ld h, ",hours]]:@"";
        durationString = minutes > 0 ? [durationString stringByAppendingString:[NSString stringWithFormat:@"%02d m, ",minutes]]:@"";
        durationString = seconds > 0 ? [durationString stringByAppendingString:[NSString stringWithFormat:@"%02d s",seconds]]:@"";
        
        return durationString;
    }
    else {
        return @"";
    }
    
}





@end


