/*
RSSFeedParser.m

Author: Makoto Kinoshita

Copyright 2004-2006 The Shiira Project. All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted 
provided that the following conditions are met:

  1. Redistributions of source code must retain the above copyright notice, this list of conditions 
  and the following disclaimer.

  2. Redistributions in binary form must reproduce the above copyright notice, this list of 
  conditions and the following disclaimer in the documentation and/or other materials provided 
  with the distribution.

THIS SOFTWARE IS PROVIDED BY THE SHIIRA PROJECT ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, 
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE SHIIRA PROJECT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
POSSIBILITY OF SUCH DAMAGE.
*/

#import "RSSFeedParser.h"
#import "RSSItemParser.h"

@implementation RSSFeedParser

//--------------------------------------------------------------//
#pragma mark -- Initialize --
//--------------------------------------------------------------//

- (id)initWithXMLNode:(NSXMLNode*)feedNode URLString:(NSString*)urlString
{
    self = [super init];
    if (!self) {
        return nil;
    }
    
    // Initialize instance variables
    _feedNode = [feedNode retain];
    _urlString = urlString;
    
    return self;
}

- (void)dealloc
{
    [_feedNode release], _feedNode = nil;
    [_urlString release], _urlString = nil;
    
    [super dealloc];
}

//--------------------------------------------------------------//
#pragma mark -- Accessors --
//--------------------------------------------------------------//

- (BOOL)isRSSNode
{
    // Check feed name
    NSString*   name;
    name = [_feedNode name];
    return [name isEqualToString:@"rss"] || 
            [name isEqualToString:@"rdf:RDF"] || 
            [name isEqualToString:@"feed"];
}

- (NSString*)URLString
{
    return _urlString;
}

- (NSString*)title
{
    // Get '/rss/channel/title'
    NSArray*    nodes;
    nodes = [_feedNode nodesForXPath:@"/rss/channel/title" error:NULL];
    if ([nodes count] == 0) {
        return nil;
    }
    
    return [[nodes objectAtIndex:0] stringValue];
}

- (NSString*)link
{
    // Get '/rss/channel/link'
    NSArray*    nodes;
    nodes = [_feedNode nodesForXPath:@"/rss/channel/link" error:NULL];
    if ([nodes count] == 0) {
        return nil;
    }
    
    return [[nodes objectAtIndex:0] stringValue];
}

- (NSString*)pubDate
{
    // Get '/rss/channel/pubDate'
    NSArray*    nodes;
    nodes = [_feedNode nodesForXPath:@"/rss/channel/pubDate" error:NULL];
    if ([nodes count] == 0) {
        return nil;
    }
    
    return [[nodes objectAtIndex:0] stringValue];
}

- (NSString*)lastBuildDate
{
    // Get '/rss/channel/lastBuildDate'
    NSArray*    nodes;
    nodes = [_feedNode nodesForXPath:@"/rss/channel/lastBuildDate" error:NULL];
    if ([nodes count] == 0) {
        return nil;
    }
    
    return [[nodes objectAtIndex:0] stringValue];
}

- (NSString*)author
{
    // Get '/rss/channel/author'
    NSArray*    nodes;
    nodes = [_feedNode nodesForXPath:@"/rss/channel/author" error:NULL];
    if ([nodes count] == 0) {
        return nil;
    }
    
    return [[nodes objectAtIndex:0] stringValue];
}

- (NSString*)description
{
    // Get '/rss/channel/description'
    NSArray*    nodes;
    nodes = [_feedNode nodesForXPath:@"/rss/channel/description" error:NULL];
    if ([nodes count] == 0) {
        return nil;
    }
    
    return [[nodes objectAtIndex:0] stringValue];
}

- (NSString*)iTunesImageURL
{
    return nil;
}

- (NSString*)iTunesAuthor
{
    return nil;
}

- (NSString*)rdfTitle
{
    // Check namespaces
    if (![(NSXMLElement*)_feedNode namespaceForPrefix:@"rdf"]) {
        return nil;
    }
    
    // Get '/rdf:RDF/channel/title'
    NSArray*    nodes;
    nodes = [_feedNode nodesForXPath:@"/rdf:RDF/channel/title" error:NULL];
    if ([nodes count] == 0) {
        return nil;
    }
    
    return [[nodes objectAtIndex:0] stringValue];
}

- (NSString*)rdfLink
{
    // Check namespaces
    if (![(NSXMLElement*)_feedNode namespaceForPrefix:@"rdf"]) {
        return nil;
    }
    
    // Get '/rdf:RDF/channel/link'
    NSArray*    nodes;
    nodes = [_feedNode nodesForXPath:@"/rdf:RDF/channel/link" error:NULL];
    if ([nodes count] == 0) {
        return nil;
    }
    
    return [[nodes objectAtIndex:0] stringValue];
}

- (NSString*)rdfDescription
{
    // Check namespaces
    if (![(NSXMLElement*)_feedNode namespaceForPrefix:@"rdf"]) {
        return nil;
    }
    
    // Get '/rdf:RDF/channel/description'
    NSArray*    nodes;
    nodes = [_feedNode nodesForXPath:@"/rdf:RDF/channel/description" error:NULL];
    if ([nodes count] == 0) {
        return nil;
    }
    
    return [[nodes objectAtIndex:0] stringValue];
}

- (NSString*)dcDate
{
    // Check namespaces
    if (![(NSXMLElement*)_feedNode namespaceForPrefix:@"dc"]) {
        return nil;
    }
    
    // Get '/rss/channel/dc:date'
    NSArray*    nodes;
    nodes = [_feedNode nodesForXPath:@"/rss/channel/dc:date" error:NULL];
    if ([nodes count] == 0) {
        return nil;
    }
    
    return [[nodes objectAtIndex:0] stringValue];
}

- (NSString*)dcCreator
{
    // Check namespaces
    if (![(NSXMLElement*)_feedNode namespaceForPrefix:@"dc"]) {
        return nil;
    }
    
    // Get '/rss/channel/dc:creator'
    NSArray*    nodes;
    nodes = [_feedNode nodesForXPath:@"/rss/channel/dc:creator" error:NULL];
    if ([nodes count] == 0) {
        return nil;
    }
    
    return [[nodes objectAtIndex:0] stringValue];
}

- (NSString*)rdfDcDate
{
    // Check namespaces
    if (![(NSXMLElement*)_feedNode namespaceForPrefix:@"rdf"] || 
        ![(NSXMLElement*)_feedNode namespaceForPrefix:@"dc"])
    {
        return nil;
    }
    
    // Get '/rdf:RD/channel/dc:creator'
    NSArray*    nodes;
    nodes = [_feedNode nodesForXPath:@"/rdf:RDF/channel/dc:creator" error:NULL];
    if ([nodes count] == 0) {
        return nil;
    }
    
    return [[nodes objectAtIndex:0] stringValue];
}

- (NSString*)rdfDcCreator
{
    // Check namespaces
    if (![(NSXMLElement*)_feedNode namespaceForPrefix:@"rdf"] || 
        ![(NSXMLElement*)_feedNode namespaceForPrefix:@"dc"])
    {
        return nil;
    }
    
    // Get '/rdf:RD/channel/dc:creator'
    NSArray*    nodes;
    nodes = [_feedNode nodesForXPath:@"/rdf:RDF/channel/dc:creator" error:NULL];
    if ([nodes count] == 0) {
        return nil;
    }
    
    return [[nodes objectAtIndex:0] stringValue];
}

- (NSString*)feedTitle
{
    // Get '/feed/title'
    NSArray*    nodes;
    nodes = [_feedNode nodesForXPath:@"/feed/title" error:NULL];
    if ([nodes count] == 0) {
        return nil;
    }
    
    return [[nodes objectAtIndex:0] stringValue];
}

- (NSString*)feedLink
{
    // Get '/feed/link'
    NSArray*    nodes;
    nodes = [_feedNode nodesForXPath:@"/feed/link" error:NULL];
    if ([nodes count] == 0) {
        return nil;
    }
    
    return [[nodes objectAtIndex:0] stringValue];
}

- (NSString*)feedUpdated
{
    // Get '/feed/updated'
    NSArray*    nodes;
    nodes = [_feedNode nodesForXPath:@"/feed/updated" error:NULL];
    if ([nodes count] == 0) {
        return nil;
    }
    
    return [[nodes objectAtIndex:0] stringValue];
}

- (NSString*)feedSubtitle
{
    // Get '/feed/subtitle'
    NSArray*    nodes;
    nodes = [_feedNode nodesForXPath:@"/feed/subtitle" error:NULL];
    if ([nodes count] == 0) {
        return nil;
    }
    
    return [[nodes objectAtIndex:0] stringValue];
}

- (NSArray*)itemNodes
{
    return [_feedNode nodesForXPath:@"/rss/channel/item" error:NULL];
}

- (NSArray*)rdfItemNodes
{
    // Check namespaces
    if (![(NSXMLElement*)_feedNode namespaceForPrefix:@"rdf"]) {
        return nil;
    }
    
    NSArray*    nodes;
    nodes = [_feedNode nodesForXPath:@"/rdf:RDF/item" error:NULL];
    
    return nodes;
}

- (NSArray*)feedEntries
{
    return [_feedNode nodesForXPath:@"/feed/entry" error:NULL];
}

//--------------------------------------------------------------//
#pragma mark -- Parse --
//--------------------------------------------------------------//

- (id)parseWithManagedObjectContext:(NSManagedObjectContext*)context
{
    // Check feed
    if (![self isRSSNode]) {
        return nil;
    }
    
    // Get feed object
    id              feed = nil;
    if (context) {
        NSFetchRequest* request;
        NSArray*        feeds;
        request = [[NSFetchRequest alloc] init];
        [request autorelease];
        [request setEntity:
                [NSEntityDescription entityForName:@"RSSFeed" inManagedObjectContext:context]];
        [request setPredicate:
                [NSPredicate predicateWithFormat:@"feedURL == %@", _urlString]];
        feeds = [context executeFetchRequest:request error:NULL];
        if ([feeds count] == 0) {
            return nil;
        }
        feed = [feeds objectAtIndex:0];
    }
    else {
        feed = [NSMutableDictionary dictionary];
        [feed setValue:_urlString forKey:@"feedURL"];
        [feed setValue:[NSMutableSet set] forKey:@"items"];
    }
    
    NSString*   str;
    NSDate*     date;
    
    // title
    str = [self title];
    if (!str) { str = [self rdfTitle]; }
    if (!str) { str = [self feedTitle]; }
    if (str) {
        [feed setValue:[str stringByReplacingCharacterReferences] forKey:@"title"];
    }
    
    // link
    str = [self link];
    if (!str) { str = [self rdfLink]; }
    if (!str) { str = [self feedLink]; }
    if (str) {
        [feed setValue:str forKey:@"link"];
    }
    
    // pubDate
    str = [self pubDate];
    if (!str) { str = [self dcDate]; }
    if (!str) { str = [self feedUpdated]; }
    if (!str) { str = [self rdfDcDate]; }
    date = [NSDate dateWithFormattedString:str];
    if (date) {
        [feed setValue:date forKey:@"pubDate"];
    }
    
    // pubDate
    str = [self lastBuildDate];
    date = [NSDate dateWithFormattedString:str];
    if (date) {
        [feed setValue:date forKey:@"lastBuildDate"];
    }
    
    // author
    str = [self dcCreator];
    if (!str) { str = [self author]; }
    if (!str) { str = [self iTunesAuthor]; }
    if (!str) { str = [self rdfDcCreator]; }
    if (str) {
        [feed setValue:str forKey:@"author"];
    }
    
    // content
    str = [self description];
    if (!str) { str = [self rdfDescription]; }
    if (str) {
        [feed setValue:str forKey:@"content"];
    }
    
    // Get items
    NSArray*    itemNodes;
    itemNodes = [self itemNodes];
    if ([itemNodes count] == 0) {
        itemNodes = [self rdfItemNodes];
    }
    if ([itemNodes count] == 0) {
        itemNodes = [self feedEntries];
    }
    if ([itemNodes count] == 0) {
        return feed;
    }
    
    // Parse items
    NSEnumerator*   enumerator;
    NSXMLNode*      itemNode;
    enumerator = [itemNodes objectEnumerator];
    while (itemNode = [enumerator nextObject]) {
        // Parse item
        RSSItemParser*  itemParser;
        id              item;
        itemParser = [[RSSItemParser alloc] initWithXMLNode:itemNode];
        item = [itemParser parseWithManagedObjectContext:context feed:feed];
        if (!item) {
            continue;
        }
        
        // Add item
        [item setValue:feed forKey:@"channel"];
        if (![[feed valueForKey:@"items"] containsObject:item]) {
            [[feed valueForKey:@"items"] addObject:item];
        }
    }
    
    // Update number of unread article numbers
    [[self class] updateNumberOfUnreadArticles:feed];
    
    return feed;
}

+ (void)updateNumberOfUnreadArticles:(id)feed
{
    // Get items
    NSArray*    items;
    items = [[feed valueForKey:@"items"] allObjects];
    
    // Get unread items
    NSArray*    unreadItems;
    unreadItems = [items filteredArrayUsingPredicate:
            [NSPredicate predicateWithFormat:@"isRead == NO"]];
    
    // Set number of unread articles
    NSNumber*   number;
    number = [feed valueForKey:@"numberOfUnreadArticles"];
    if ([number intValue] != [unreadItems count]) {
        [feed setValue:[NSNumber numberWithInt:[unreadItems count]] 
                forKey:@"numberOfUnreadArticles"];
    }
}

@end
