//
//  Created by Björn Sållarp on 4/25/11.
//  NO Copyright, NO rights reserved.
//
//  Use this code any way you like. If you do like it, please
//  link to my blog and/or write a friendly comment. Thank you!
//
//  Read my blog @ http://blog.sallarp.com
//

#import "BSAtomFeedEntry.h"
#import "BSAtomFeedCustomElement.h"
#import "BSAtomFeedLink.h"

static NSString * NoNilString(NSString * input) {
	if (input) return input;
	return @"";
}

@implementation BSAtomFeedEntry
@synthesize summary;
@synthesize customElements;
@synthesize content;

+ (BSAtomFeedEntry *)entry
{
    return [[self alloc] init];
}

- (NSArray *)customElementsWithName:(NSString *)name
{
    NSMutableArray *matchingElements = nil;
	
    for (BSAtomFeedCustomElement *elem in self.customElements) {
        if ([elem.name isEqualToString:name]) {
            if (!matchingElements) {
                matchingElements = [NSMutableArray array];
            }
            [matchingElements addObject:elem];
        }
    }
	
    return matchingElements;
}

- (NSString *)contentTypeString {
	switch (self.content.contentType) {
		case kAtomText:
			return @"text/plain";
		case kAtomHTML:
			return @"text/html";
		case kAtomXHTML:
			return @"text/xhtml";
	}
	return @"";
}

- (NSDictionary *)dictionaryRepresentation {

	NSMutableDictionary * rep = @{
			 @"title":NoNilString(self.title.content),
			 @"summary":NoNilString(self.summary.content),
			 @"content":NoNilString(self.content.content),
			 //@"contentType":self.contentTypeString,
			 }.mutableCopy;
	
	
	NSString * thumbnail = self.thumbnail;
	if (thumbnail) {
		rep[@"thumbnail"] = thumbnail;
	}

	if (self.links.count) {
		BSAtomFeedLink * firstLink = self.links[0];
		rep[@"link"] = firstLink.href;
	}

	return rep;
	

}

- (NSString *)thumbnail {
	NSArray * elm = [self customElementsWithName:@"media:thumbnail"];
	if (!elm.count) return nil;
	NSDictionary * attributes = [(BSAtomFeedCustomElement *)[elm objectAtIndex:0] attributes];
	return [attributes objectForKey:@"url"];
}


@end
