/*
SRXMLDocument.m

Author: Makoto Kinoshita

Copyright 2004 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 <libxml/parser.h>
#import <libxml/tree.h>
#import <libxslt/xsltInternals.h>
#import <libxslt/transform.h>
#import <libxslt/xsltutils.h>
#import "SRXMLNodePrivate.h"
#import "SRXMLElement.h"
#import "SRXMLDocument.h"
#import "SRXMLDocumentPrivate.h"

@interface NSString (CharacterReference)
- (NSString*)stringByReplacingCharacterReferences;
@end

#pragma mark -

@interface SRXMLDocumentPrivate : NSObject
{
@public
	xmlDocPtr	_doc;
}
@end

@implementation SRXMLDocumentPrivate

- (id)init
{
	self = [super init];
	if (!self) {
		return nil;
	}
	
	// Initialize instance variables
	_doc = NULL;
	
	return self;
}

- (void)dealloc
{
	if (_doc) {
		xmlFreeDoc(_doc);
	}
	
	[super dealloc];
}

@end

#pragma mark -

@implementation SRXMLDocument

#pragma mark -- Initialize --

- (id)init
{
	self = [super initWithKind:SRXMLDocumentKind];
	if (!self) {
		return nil;
	}
	
	// Initialize instance variables
	_documentPrivate = [[SRXMLDocumentPrivate alloc] init];
	[self _setRootDocument:self];
	
	return self;
}

- (id)initWithContentsOfURL:(NSURL*)url options:(unsigned int)mask error:(NSError**)error
{
	self = [super initWithKind:SRXMLDocumentKind];
	if (!self) {
		return nil;
	}
	
	// Initialize instance variables
	_documentPrivate = [[SRXMLDocumentPrivate alloc] init];
	[self _setRootDocument:self];
	
	// For file URL
	if ([url isFileURL]) {
    	// Parse XML file
		NSString*	URLString;
		URLString = [url absoluteString];
		_documentPrivate->_doc = xmlReadFile([URLString cString], NULL, XML_PARSE_NOBLANKS);
        [self _setNode:(xmlNodePtr)_documentPrivate->_doc];
	}
	
    if (error) {
        *error = nil;
    }
    
	return self;
}

- (id)initWithData:(NSData*)data options:(unsigned int)mask error:(NSError**)error
{
	self = [super initWithKind:SRXMLDocumentKind];
	if (!self) {
		return nil;
	}
	
	// Initialize instance variables
	_documentPrivate = [[SRXMLDocumentPrivate alloc] init];
	[self _setRootDocument:self];
	
    // Parse XML data
    _documentPrivate->_doc = xmlReadMemory([data bytes], [data length], NULL, NULL, XML_PARSE_NOBLANKS);
    [self _setNode:(xmlNodePtr)_documentPrivate->_doc];
	
    if (error) {
        *error = nil;
    }
    
	return self;
}

- (id)initWithXMLString:(NSString*)string options:(unsigned int)mask error:(NSError**)error
{
	self = [super initWithKind:SRXMLDocumentKind];
	if (!self) {
		return nil;
	}
	
    NSLog(@"- [SRXMLDocument initWithXMLString:options:error:], Not implemented yet");
    
    if (error) {
        *error = nil;
    }
    
    return self;
}

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

#pragma mark -- Root element --

- (SRXMLElement*)rootElement
{
	if (!_documentPrivate->_doc) {
		return nil;
	}
	
	// Get root element
	xmlNodePtr	rootNode;
	rootNode = xmlDocGetRootElement(_documentPrivate->_doc);
	if (!rootNode) {
		return nil;
	}
	
	// Create root element object
	SRXMLElement*	element;
	element = [[SRXMLElement alloc] initWithName:
			[NSString stringWithUTF8String:(const char *)rootNode->name]];
	[element autorelease];
	[element _setNode:rootNode];
    [element _setRootDocument:self];
    
	return element;
}

#pragma mark -- XSLT transform --

- (id)objectByApplyingXSLTAtURL:(NSURL*)xsltURL 
		arguments:(NSDictionary*)arguments 
		error:(NSError**)error
{
    if (error) {
        *error = nil;
    }
    
	if (!_documentPrivate->_doc) {
		return nil;
	}
	
	// For file URL
	if ([xsltURL isFileURL]) {
		// Get path
		NSString*	path;
		path = [xsltURL path];
		
		// Parse style sheet
		xsltStylesheetPtr	stylesheet;
		stylesheet = xsltParseStylesheetFile((const xmlChar*)[path cString]);
		
		// Apply stylesheet
		xmlDocPtr	result;
		const char*	params[1];
		params[0] = NULL;
		result = xsltApplyStylesheet(stylesheet, _documentPrivate->_doc, params);
		if (!result) {
			return nil;
		}
		
		// Create document
		SRXMLDocument*	document;
		document = [SRXMLNode document];
		document->_documentPrivate->_doc = result;
		
		xsltFreeStylesheet(stylesheet);
		
		return document;
	}
	
	return nil;
}

#pragma mark -- XML data --

- (NSData*)XMLData
{
	xmlChar*	dumpedData;
	int			size;
	xmlDocDumpMemory(_documentPrivate->_doc, &dumpedData, &size);
	if (!dumpedData || size == 0) {
		return nil;
	}
	
	return [NSData dataWithBytesNoCopy:dumpedData length:size freeWhenDone:YES];
}

- (NSData*)XMLDataWithOptions:(unsigned int)options
{
    return [self XMLData];
}

@end

#pragma mark -

@implementation SRXMLDocument (private)

- (xmlDocPtr)_doc
{
	return _documentPrivate->_doc;
}

@end
