//
// Created by Nicky Romeijn on 23-06-16.
// Copyright (c) 2016 Adversitement. All rights reserved.
//

#import "Dispatcher.h"
#import "Device.h"
#include <ifaddrs.h>
#include <arpa/inet.h>
#import "CoreTelephony/CTCarrier.h"

@implementation Dispatcher {
    
}

- (id)init:(NSString *)appName; {
    self = [super init];
    _appName = appName;
    return self;
}

- (NSMutableDictionary *)getGeneralInfo; {
    
    Device *d = [[Device alloc] init];
    NSMutableDictionary *data = @{
                                  @"AppId" : _appName,
                                  @"ip" : [self getIPAddress],
                                  @"connection" : [self getConnectionType],
                                  @"operatingSystem":  [[UIDevice currentDevice] systemVersion],
                                  @"device":d.deviceName
                                  };
    
    return data;
}

- (void)dispatch:(NSString *)endpoint :(NSMutableArray *)funnel; {
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    NSLocale *enUSPOSIXLocale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
    [dateFormatter setLocale:enUSPOSIXLocale];
    [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];
    
    NSDate *now = [NSDate date];
    NSString *iso8601String = [dateFormatter stringFromDate:now];
    
    NSDictionary *data = @{
                           @"application" :  [self getGeneralInfo],
                           @"tracked" : funnel,
                           @"identity":_identity,
                           @"alias":_alias,
                           @"trackingDateTime":[iso8601String stringByReplacingOccurrencesOfString:@"+" withString:@"%2B"]
                           };
    
    
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:data
                                                       options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
                                                         error:&error];
    
    if (!jsonData) {
        NSLog(@"Got an error: %@", error);
    } else {
        NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        //        jsonString = [jsonString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSString *post = [NSString stringWithFormat:@"data=%@", jsonString];
        NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding];
        NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
        [request setURL:[NSURL URLWithString:endpoint]];
        [request setHTTPMethod:@"POST"];
        [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
        [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
        //        [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        [request setHTTPBody:postData];
        NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
        if (conn) {
            NSString *sample = [[NSString alloc] initWithData:postData encoding:NSUTF8StringEncoding];
            NSLog(@"lenght (%@) Funnel-UTF8 -> ( %@ ) has been dispatched to: %@", postLength, sample, endpoint);
            [funnel removeAllObjects];
        } else {
            NSLog(@"Connection could not be made");
        }
    }
}

-(void) setAliasAndIdentity:(NSString*)alias :(NSString*)identity; {
    _alias = alias;
    _identity = identity;
}

- (NSString *)getIPAddress {
    NSString *address = @"error";
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    int success = 0;
    // retrieve the current interfaces - returns 0 on success
    success = getifaddrs(&interfaces);
    if (success == 0) {
        // Loop through linked list of interfaces
        temp_addr = interfaces;
        while (temp_addr != NULL) {
            if (temp_addr->ifa_addr->sa_family == AF_INET) {
                // Check if interface is en0 which is the wifi connection on the iPhone
                if ([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
                    // Get NSString from C String
                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *) temp_addr->ifa_addr)->sin_addr)];
                    
                }
                
            }
            
            temp_addr = temp_addr->ifa_next;
        }
    }
    // Free memory
    freeifaddrs(interfaces);
    return address;
}

- (NSString *)getConnectionType {
    NSString *connectionType;
    Reachability *reachability = [Reachability reachabilityForInternetConnection];
    [reachability startNotifier];
    
    NetworkStatus status = [reachability currentReachabilityStatus];
    
    if (status == NotReachable) {
        connectionType = @"None";
        //No internet
    }
    else if (status == ReachableViaWiFi) {
        connectionType = @"Wifi";
        //WiFi
    }
    else if (status == ReachableViaWWAN) {
        connectionType = @"WWAN";
        
        
        //connection type
        CTTelephonyNetworkInfo *netinfo = [[CTTelephonyNetworkInfo alloc] init];
        _carrier = [[netinfo subscriberCellularProvider] carrierName];
        
        if ([netinfo.currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyGPRS]) {
            connectionType = @"2G";
        } else if ([netinfo.currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyEdge]) {
            connectionType = @"2G";
        } else if ([netinfo.currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyWCDMA]) {
            connectionType = @"3G";
        } else if ([netinfo.currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyHSDPA]) {
            connectionType = @"3G";
        } else if ([netinfo.currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyHSUPA]) {
            connectionType = @"3G";
        } else if ([netinfo.currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyCDMA1x]) {
            connectionType = @"2G";
        } else if ([netinfo.currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyCDMAEVDORev0]) {
            connectionType = @"3G";
        } else if ([netinfo.currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyCDMAEVDORevA]) {
            connectionType = @"3G";
        } else if ([netinfo.currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyCDMAEVDORevB]) {
            connectionType = @"3G";
        } else if ([netinfo.currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyeHRPD]) {
            connectionType = @"3G";
        } else if ([netinfo.currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyLTE]) {
            connectionType = @"4G";
        }
        
    }
    
    return connectionType;
}


@end
