//
//  AdswizzParser.m
//  Allzic
//
//  Created by Alia Bourouis on 15/05/14.
//  Copyright (c) 2014 Alia Bourouis. All rights reserved.
//

#import "AdswizzParser.h"
#import "AppDelegate.h"

@implementation AdswizzParser

@synthesize isParseError,dataDictionary;

- (id)init {
	
    self = [super init];
    if (self != nil) {
        // Initialization code.
		appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    }
    return self;
}


//-----------------------------------------
//		NSURLConnection Delegate
//-----------------------------------------

- (void)httpConnection:(NSString *)url {
	
    isParseError = NO;
    if(!url) {
        url = @"";
    }
    NSLog(@"HTTP CONNECTION TO URL : %@",url);
	NSURLCache *sharedCache = [NSURLCache sharedURLCache];
	[sharedCache removeAllCachedResponses];
	
	NSMutableURLRequest *serverRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]  cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0];
	[serverRequest setValue:@"no-store, no-cache, must-revalidate, post-check=0, pre-check=0" forHTTPHeaderField:@"Cache-Control"];
	[serverRequest addValue:@"no-cache" forHTTPHeaderField:@"Pragma"];
	serverConnection = nil;
	serverConnection = [[NSURLConnection alloc] initWithRequest:serverRequest delegate:self];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
	
	receivedData = nil;
    receivedData = [[NSMutableData alloc]init];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
	
	if(data != nil) {
		if(receivedData == nil) receivedData = [[NSMutableData alloc]init];
		[receivedData appendData:data];
	}
	else {
		NSLog(@"data is nil");
	}
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
	
    if (receivedData != nil) {
		NSXMLParser *parser = [[NSXMLParser alloc] initWithData:receivedData];
		[parser setDelegate:self];
		[parser parse];
	} else {
        [appDelegate.dataController parseFinished:self];
    }
    [serverConnection cancel];
	receivedData = nil;
	serverConnection = nil;
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
	
	NSLog(@"Connection failed with error : %@",error);
	if(receivedData != nil) receivedData = nil;
	if(serverConnection != nil) serverConnection = nil;
    isParseError = YES;
    [appDelegate.dataController parseFinished:self];
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {
    
    //NSLog(@"%@<%@>",parsedString,elementName);
    if ([elementName isEqualToString:@"VAST"]){
        dataDictionary = [[NSMutableDictionary alloc] init];
	}
    else if ([elementName isEqualToString:@"Companion"]){
        if ([[attributeDict objectForKey:@"width"] intValue] > [[attributeDict objectForKey:@"height"] intValue]) {
            [dataDictionary setValue:@"" forKey:@"banner"];
            [dataDictionary setValue:[NSNumber numberWithInt:[[attributeDict objectForKey:@"width"] intValue]] forKey:@"bannerWidth"];
            [dataDictionary setValue:[NSNumber numberWithInt:[[attributeDict objectForKey:@"height"] intValue]] forKey:@"bannerHeight"];
        } else if ([[attributeDict objectForKey:@"height"] intValue] > [[attributeDict objectForKey:@"width"] intValue]) {
            [dataDictionary setValue:@"" forKey:@"interstitial"];
        }
	}
    else if ([elementName isEqualToString:@"Tracking"]){
        if ([attributeDict objectForKey:@"event"] != nil && [[attributeDict objectForKey:@"event"] isEqualToString:@"creativeView"]) {
            attribute = @"creativeView";
        } else if ([attributeDict objectForKey:@"event"] != nil && [[attributeDict objectForKey:@"event"] isEqualToString:@"start"]) {
            attribute = @"start";
        } else if ([attributeDict objectForKey:@"event"] != nil && [[attributeDict objectForKey:@"event"] isEqualToString:@"firstQuartile"]) {
            attribute = @"firstQuartile";
        } else if ([attributeDict objectForKey:@"event"] != nil && [[attributeDict objectForKey:@"event"] isEqualToString:@"midpoint"]) {
            attribute = @"midpoint";
        } else if ([attributeDict objectForKey:@"event"] != nil && [[attributeDict objectForKey:@"event"] isEqualToString:@"thirdQuartile"]) {
            attribute = @"thirdQuartile";
        } else if ([attributeDict objectForKey:@"event"] != nil && [[attributeDict objectForKey:@"event"] isEqualToString:@"complete"]) {
            attribute = @"complete";
        } else {
            attribute = nil;
        }
	}
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
	
	//NSLog(@"%@</%@>",parsedString,elementName);
	if ([elementName isEqualToString:@"VAST"]) {
        [appDelegate.dataController parseFinished:self];
	}
    else if ([elementName isEqualToString:@"Companion"]) {
        if ([dataDictionary valueForKey:@"banner"] != nil && [[dataDictionary valueForKey:@"banner"] length] == 0) {
            [dataDictionary setValue:@"OK" forKey:@"banner"];
        } else if ([dataDictionary valueForKey:@"interstitial"] != nil && [[dataDictionary valueForKey:@"insterstitial"] length] == 0) {
            [dataDictionary setValue:@"OK" forKey:@"interstitial"];
        }
	}
    else if ([elementName isEqualToString:@"StaticResource"]) {
        if ([dataDictionary valueForKey:@"banner"] != nil && [[dataDictionary valueForKey:@"banner"] length] == 0) {
            [dataDictionary setValue:parsedString forKey:@"bannerImage"];
        } else if ([dataDictionary valueForKey:@"interstitial"] != nil && [[dataDictionary valueForKey:@"insterstitial"] length] == 0) {
            [dataDictionary setValue:parsedString forKey:@"interstitialImage"];
        }
	}
    else if ([elementName isEqualToString:@"CompanionClickThrough"]) {
        if ([dataDictionary valueForKey:@"banner"] != nil && [[dataDictionary valueForKey:@"banner"] length] == 0) {
            [dataDictionary setValue:parsedString forKey:@"bannerLink"];
        } else if ([dataDictionary valueForKey:@"interstitial"] != nil && [[dataDictionary valueForKey:@"insterstitial"] length] == 0) {
            [dataDictionary setValue:parsedString forKey:@"interstitialLink"];
        }
    }
    else if ([elementName isEqualToString:@"Tracking"]){
        if (attribute != nil && [attribute isEqualToString:@"creativeView"] && [dataDictionary valueForKey:@"banner"] != nil && [[dataDictionary valueForKey:@"banner"] length] == 0) {
           [dataDictionary setValue:parsedString forKey:@"bannerTracking"];
        } else if (attribute != nil && [attribute isEqualToString:@"creativeView"] && [dataDictionary valueForKey:@"interstitial"] != nil && [[dataDictionary valueForKey:@"insterstitial"] length] == 0) {
            [dataDictionary setValue:parsedString forKey:@"interstitialTracking"];
        } else if (attribute != nil && [attribute isEqualToString:@"start"]) {
            [dataDictionary setValue:parsedString forKey:@"audioTrackingStart"];
        } else if (attribute != nil && [attribute isEqualToString:@"firstQuartile"]) {
            [dataDictionary setValue:parsedString forKey:@"audioTrackingFirstQuartile"];
        } else if (attribute != nil && [attribute isEqualToString:@"midpoint"]) {
            [dataDictionary setValue:parsedString forKey:@"audioTrackingMidpoint"];
        } else if (attribute != nil && [attribute isEqualToString:@"thirdQuartile"]) {
            [dataDictionary setValue:parsedString forKey:@"audioTrackingThirdQuartile"];
        } else if (attribute != nil && [attribute isEqualToString:@"complete"]) {
            [dataDictionary setValue:parsedString forKey:@"audioTrackingComplete"];
        }
	}
    else if ([elementName isEqualToString:@"Duration"]){
        [dataDictionary setValue:parsedString forKey:@"audioDuration"];
    }
    else if ([elementName isEqualToString:@"MediaFile"]){
        [dataDictionary setValue:parsedString forKey:@"audioMp3"];
    }
    else if ([elementName isEqualToString:@"Impression"]){
        [dataDictionary setValue:parsedString forKey:@"impression"];
    }
    parsedString = @"";
}


- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
    
    parsedString = [NSString stringWithFormat:@"%@%@",parsedString,[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
}


- (void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock {
	
    parsedString = [[[NSString alloc] initWithData:CDATABlock encoding:NSUTF8StringEncoding]stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}


- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError {
	
	NSLog(@"Error while parsing XML : %@", [parseError description] );
    [appDelegate.dataController parseFinished:self];
}

@end
