//
//  SFSCryptoInitializer.m
//  SFS2X
//
//  Created by Lapo on 29/05/15.
//  Copyright (c) 2015 gotoAndPlay()
//

#import "SFSCryptoInitializer.h"
#import "SFSBase64.h"
#import "SFSCryptoKey.h"
#import "BitSwarmClient.h"

static const NSString* KEY_SESSION_TOKEN = @"SessToken";
static const NSString* TARGET_SERVLET = @"/BlueBox/CryptoManager";

@implementation SFSCryptoInitializer
{
    // HttpRequest instance var
}


-(id)initWithSFS:(SmartFox2XClient *)sfs
{
    if ((self = [super init]))
    {
        _sfs = sfs;
    }
    
    return self;
}


/*
 Uses NSURLSession, required by iOS9 and for compiling with XCode 7.1 and higher
 
*/
-(void) execute
{
    NSString* targetUrl = [NSString stringWithFormat:@"https://%@:%ld%@", _sfs.config.host, (long)_sfs.config.httpsPort, TARGET_SERVLET];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:targetUrl]];
    [request setHTTPMethod:@"POST"];
    
    // URL encode the request params
    NSString* postParams = [NSString stringWithFormat:@"%@=%@", KEY_SESSION_TOKEN, _sfs.sessionToken];
    
    // Set request len
    [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[postParams length]] forHTTPHeaderField:@"Content-length"];
    
    // Set body of request
    [request setHTTPBody:[postParams dataUsingEncoding:NSUTF8StringEncoding]];
  
    NSURLSession *session = [NSURLSession sharedSession];
    
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                            completionHandler:
                                  ^(NSData *data, NSURLResponse *response, NSError *error)
                                  {
                                      if (error)
                                          [self connection:nil didFailWithError:error];
                                      else
                                          [self connection:nil didReceiveData:data];
                                  }];
    
    [task resume];
   
}


// Delegates

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    NSString* response = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSData* binData = [SFSBase64 decode:response];

    SFSCryptoKey* cKey = [[SFSCryptoKey alloc] init];
    
    @try 
    {
        // Extract first 16 bytes
        cKey.key = [binData subdataWithRange: (NSRange) {0, 16}];
        
        // Extract last 16 bytes
        cKey.iv = [binData subdataWithRange: (NSRange) {16, 16}];

        _sfs.bitSwarm.cryptoKey = cKey;

        //NSLog(@"Data ok: %@", response);
        //NSLog(@"Key: %@, IV: %@", cKey.key, cKey.iv);
        
        // Trigger success event
        NSMutableDictionary* evtParams = [NSMutableDictionary dictionary];
        [evtParams setObject:[NSNumber numberWithBool:YES] forKey:@"success"];
        
        if ([_sfs.delegate respondsToSelector:@selector(onCryptoInit:)])
            [_sfs.delegate onCryptoInit:[[SFSEvent alloc] initWithType:SFSEvent_CRYPTO_INIT params:evtParams]];
        
    }   
    
    @catch (NSException* err)
    {
        NSLog(@"InitCrypto decode error: %@", err);

        // Fire failure event
        NSMutableDictionary* evtParams = [NSMutableDictionary dictionary];
        [evtParams setObject:[NSNumber numberWithBool:NO] forKey:@"success"];
        
        if ([_sfs.delegate respondsToSelector:@selector(onCryptoInit:)])
            [_sfs.delegate onCryptoInit:[[SFSEvent alloc] initWithType:SFSEvent_CRYPTO_INIT params:evtParams]];
            
    }
    
}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)err
{
    NSLog(@"Error during InitCrypto connection: %@", err);

    NSMutableDictionary* evtParams = [NSMutableDictionary dictionary];
    [evtParams setObject:[NSNumber numberWithBool:NO] forKey:@"success"];
    [evtParams setObject:[err localizedDescription] forKey:@"errorMsg"];
    
    if ([_sfs.delegate respondsToSelector:@selector(onCryptoInit:)])
        [_sfs.delegate onCryptoInit:[[SFSEvent alloc] initWithType:SFSEvent_CRYPTO_INIT params:evtParams]];
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"HTTPS connection success");
}

@end
