//
//  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 "BSAtomFeed.h"
#import "BSAtomFeedPerson.h"
#import "BSAtomFeedEntry.h"
#import "BSAtomFeedLink.h"

@implementation NSArray (Map)

- (NSArray *)mapObjectsUsingBlock:(id (^)(id obj, NSUInteger idx))block {
    NSMutableArray *result = [NSMutableArray arrayWithCapacity:[self count]];
    [self enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        [result addObject:block(obj, idx)];
    }];
    return result;
}

@end


@implementation BSAtomFeed

+ (BSAtomFeed *)atomFeed
{
    return [[self alloc] init];
}


- (void)addEntry:(BSAtomFeedEntry *)entry
{
    if (self.entries == nil) {
        self.entries = [NSMutableArray array];
    }
    
    [self.entries addObject:entry];
}


- (NSDictionary *)dictionaryRepresentation {
	
	NSArray * entries = [self.entries mapObjectsUsingBlock:^id(BSAtomFeedEntry * entry, NSUInteger idx) {
		return entry.dictionaryRepresentation;
	}];
	if (!entries) entries = @[];

	
	NSMutableDictionary * rep = @{}.mutableCopy;
	
	if (self.title.content)		rep[@"title"] = self.title.content;
	if (self.subtitle.content.length)	rep[@"subtitle"] = self.subtitle.content;
	if (self.icon)				rep[@"icon"] = self.icon;
	if (self.logo)				rep[@"logo"] = self.logo;
	if (self.rights.content)	rep[@"rights"] = self.rights.content;
	if (self.links.count)		{
		BSAtomFeedLink * firstLink = self.links[0];
		rep[@"link"] = firstLink.href;
	}

	rep[@"entry"] = entries;
	
	
	return rep;
	
}

@end

