//
//  WebserviceClient.m
//  ipbc-Client
//
//  Created by Gerrit Linnemann on 28.10.13.
//  Copyright (c) 2013 Adawim UG (haftungsbeschränkt). All rights reserved.
//

#import "WebserviceClient.h"
#import "WebServiceConstants.h"
#import "Reachability.h"

@implementation WebserviceClient

-(void)awakeFromNib {
    updateTimer = [NSTimer scheduledTimerWithTimeInterval: 4
                                             target: self
                                           selector: @selector(tick:)
                                           userInfo: nil
                                            repeats: YES];
    
    isRequestRunning = NO;
    
    isNetworkAvailable = NO;
    [self checkNetworkAvailability];
}

- (void)tick:(NSTimer *)theTimer {
    if(isNetworkAvailable && !isRequestRunning) {
        [self updateDomain];
    } else {
        // else for logging only
        
        if(!isNetworkAvailable) {
            NSLog(@"no ip update, 'cause network unavailable");
        }
        if(isRequestRunning) {
            NSLog(@"no ip update, 'cause of active request");
        }
    }
}

-(BOOL)updateDomain {
    usersIPv4 = [self fetchIPv4];
    NSString *storedIPv4 = [[NSUserDefaults standardUserDefaults] stringForKey:@"value.ip.ipv4"];
    if(storedIPv4 == nil) {
        [[NSUserDefaults standardUserDefaults] setObject:usersIPv4 forKey:@"value.ip.ipv4"];
    }
    
    BOOL updateResult = NO;
    
    if([self checkUpdateNeeded]) {
        NSLog(@"update resource: %@", WS_RESOURCE);
        updateResult = [self doWebServiceUpdate];
    } else {
        NSLog(@"no update needed");
    }
    
    return updateResult;
}

-(void)checkNetworkAvailability {
    // Allocate a reachability object
    Reachability* reach = [Reachability reachabilityWithHostname:WS_BASE];

    // Set the blocks
    reach.reachableBlock = ^(Reachability*reach)
    {
        NSLog(@"%@ REACHABLE", WS_BASE);
        isNetworkAvailable = YES;
    };
    
    reach.unreachableBlock = ^(Reachability*reach)
    {
        NSLog(@"%@ UNREACHABLE", WS_BASE);
        isNetworkAvailable = NO;
    };
    
    // Start the notifier, which will cause the reachability object to retain itself!
    [reach startNotifier];
}

-(BOOL)checkUpdateNeeded {
    NSString *storedIPv4 = [[NSUserDefaults standardUserDefaults] stringForKey:@"value.ip.ipv4"];
    NSString *fetchedIPv4 = usersIPv4;
    //return YES;
    if(storedIPv4 == nil) {
        NSLog(@"stored IPv4 NULL");
        return YES;
    } else if(fetchedIPv4 == nil) {
        NSLog(@"fetched IPv4 NULL");
        return NO;
    } else {
        BOOL changed = ![storedIPv4 isEqualToString:fetchedIPv4];
        NSLog(@"compare stored %@ with %@. Changed: %@", storedIPv4, fetchedIPv4, (changed ? @"yes" : @"no"));
        return changed;
    }
}

-(BOOL)doWebServiceUpdate {
    isRequestRunning = YES;
    
    NSString *settingTempName = [[NSUserDefaults standardUserDefaults] stringForKey:@"setting.name"];
    NSString *settingTempToken = [[NSUserDefaults standardUserDefaults] stringForKey:@"setting.token"];
    
    if([settingTempName length] > 0 && [settingTempToken length] > 0) {
        NSLog(@"update ip to %@", usersIPv4);
        
        NSURL *url = [NSURL URLWithString:WS_RESOURCE];
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
        [request setHTTPMethod:@"POST"];
        [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

        NSDictionary *tmp = [[NSDictionary alloc] initWithObjectsAndKeys:
                             settingTempName, @"domain",
                             settingTempToken, @"token",
                             nil];
        NSError *error;
        NSData *postData = [NSJSONSerialization dataWithJSONObject:tmp options:0 error:&error];
        [request setHTTPBody:postData];

        /*NSData *resultData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
         NSString *strData = [[NSString alloc]initWithData:resultData encoding:NSUTF8StringEncoding];
         NSLog(@"resultData: %@", strData);*/

        [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *resultData, NSError *error) {
            NSString *strData = [[NSString alloc]initWithData:resultData encoding:NSUTF8StringEncoding];
            NSLog(@"resultData: %@", strData);
        
            // locally save posted ip
            [[NSUserDefaults standardUserDefaults] setObject:usersIPv4 forKey:@"value.ip.ipv4"];
        
            isRequestRunning = NO;
        }];
    
        return YES;
    } else {
        return NO;
    }
}

-(NSString *)fetchIPv4 {
    NSURL *myIpAdress = [NSURL URLWithString:WS_GET_USERS_IP_SERVICE];
    NSString *contentOfURL = [NSString stringWithContentsOfURL:myIpAdress encoding:NSUTF8StringEncoding error:NULL];
    NSString *contentTrimmed = [contentOfURL stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

    //NSLog(@"fetched IPv4: %@", contentTrimmed);
    return contentTrimmed;
}

@end
