/*
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"

#import "HMFoundationEx.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
{
    // Create item object
    NSManagedObject*    item;
    item = [NSEntityDescription insertNewObjectForEntityForName:@"RSSItem" 
            inManagedObjectContext:context];
    if (!item) {
        return nil;
    }
    
    NSString*   str;
    
    // title
    str = [self title];
    if (str) {
        [item setValue:[str stringByReplacingCharacterReferences] forKey:@"title"];
    }
    
    // link
    str = [self link];
    if (str) {
        [item setValue:str forKey:@"link"];
    }
    
    // date
    str = [self pubDate];
    if (!str) { str = [self dcDate]; }
    if (!str) { str = [self created]; }
    if (!str) { str = [self updated]; }
    if (!str) { str = [self modified]; }
    if (!str) { str = [self issued]; }
    NSDate* date = nil;
    if (str) {
        date = [NSDate dateWithFormattedString:str];
    }
    if (!date) { date = [NSDate date]; }
    if (date) {
        [item setValue:date forKey:@"date"];
    }
    
    // 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
