/*
RSSItemParser.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 "RSSItemParser.h"

@implementation RSSItemParser

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

- (id)initWithXMLNode:(NSXMLNode*)itemNode
{
    self = [super init];
    if (!self) {
        return nil;
    }
    
    // Initialize instance variables
    _itemNode = [itemNode retain];
    
    return self;
}

- (void)dealloc
{
    [_itemNode release];
    
    [super dealloc];
}

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

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

- (NSString*)link
{
    // Get 'link'
    NSArray*    nodes;
    nodes = [_itemNode nodesForXPath:@"link" error:NULL];
    if ([nodes count] == 0) {
        return nil;
    }
    
    if ([nodes count] == 1) {
        NSString*   link;
        link = [[nodes objectAtIndex:0] stringValue];
        if ([link length] > 0) {
            return link;
        }
    }
    
    // Check links
    NSEnumerator*   enumerator;
    NSXMLNode*      linkNode;
    enumerator = [nodes objectEnumerator];
    while (linkNode = [enumerator nextObject]) {
        // Get type attribute
        NSXMLNode*  typeNode;
        typeNode = [(NSXMLElement*)linkNode attributeForName:@"type"];
        
        // For text/html
        if ([[typeNode stringValue] isEqualToString:@"text/html"]) {
            // Get href attribute
            return [[(NSXMLElement*)linkNode attributeForName:@"href"] stringValue];
        }
    }
    
    return nil;
}

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

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

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

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

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

- (NSString*)contentEncoded
{
    // Check namespaces
    if (![[[_itemNode rootDocument] rootElement] namespaceForPrefix:@"content"]) {
        return nil;
    }
    
    // Get 'content:encoded'
    NSArray*    nodes;
    nodes = [_itemNode nodesForXPath:@"content:encoded" error:NULL];
    if ([nodes count] == 0) {
        return nil;
    }
    
    return [[nodes objectAtIndex:0] stringValue];
}

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

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

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

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

- (NSString*)authorName
{
    // Check namespaces
    if (![[[_itemNode rootDocument] rootElement] namespaceForPrefix:@"author"]) {
        return nil;
    }
    
    // Get 'author:name'
    NSArray*    nodes;
    nodes = [_itemNode nodesForXPath:@"author:name" error:NULL];
    if ([nodes count] == 0) {
        return nil;
    }
    
    return [[nodes objectAtIndex:0] stringValue];
}

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

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

- (id)parseWithManagedObjectContext:(NSManagedObjectContext*)context feed:(id)feed
{
    // title
    NSString*   title;
    title = [self title];
    if (!title) {
        return nil;
    }
    title = [title stringByReplacingCharacterReferences];
    if ([title rangeOfCharacterFromSet:[NSCharacterSet newLineCharacterSet]].location != NSNotFound) {
        NSMutableString*    string;
        string = [NSMutableString stringWithString:title];
        [string replaceOccurrencesOfString:@"\n" withString:@" " 
                options:0 range:NSMakeRange(0, [string length])];
        title = string;
    }
    
    // link
    NSString*   link;
    link = [self link];
    if (!link) {
        return nil;
    }
    
    // date
    NSString*   dateStr;
    dateStr = [self pubDate];
    if (!dateStr) { dateStr = [self dcDate]; }
    if (!dateStr) { dateStr = [self created]; }
    if (!dateStr) { dateStr = [self updated]; }
    if (!dateStr) { dateStr = [self modified]; }
    if (!dateStr) { dateStr = [self issued]; }
    NSDate* date = nil;
    if (dateStr) {
        date = [NSDate dateWithFormattedString:dateStr];
    }
    if (!date) {
        date = [feed valueForKey:@"pubDate"];
        if (!date) {
            date = [NSDate date];
        }
    }
    
    // Check item is already exited or not
    NSEnumerator*   enumerator;
    id              item;
    enumerator = [[feed valueForKey:@"items"] objectEnumerator];
    while (item = [enumerator nextObject]) {
        if ([title isEqualToString:[item valueForKey:@"title"]] || 
            [link isEqualToString:[item valueForKey:@"link"]] || 
            [date isEqual:[item valueForKey:@"date"]])
        {
            // Already exited
            return nil;
        }
    }
    
    // Create item object
    if (context) {
        item = [NSEntityDescription insertNewObjectForEntityForName:@"RSSItem" 
                inManagedObjectContext:context];
        if (!item) {
            return nil;
        }
    }
    else {
        item = [NSMutableDictionary dictionary];
    }
    
    // Set item attributes
    [item setValue:title forKey:@"title"];
    [item setValue:link forKey:@"link"];
    [item setValue:date forKey:@"date"];
    
    NSString*   str;
    
    // itemDescriptoin
    str = [self contentEncoded];
    if (!str) { str = [self content]; }
    if (!str) { str = [self description]; }
    if (str) {
        [item setValue:str forKey:@"content"];
    }
    
    // author
    str = [self author];
    if (!str) { str = [self dcCreator]; }
    if (!str) { str = [self authorName]; }
    if (str) {
        [item setValue:str forKey:@"author"];
    }
    
    return item;
}

@end
