#!/usr/bin/env ruby


$LOAD_PATH.unshift '../../lib/' # use dev't copy of library for testing.

require 'test/unit'

require 'basicrdf'
# require 'squish'

class TC_RedRubyTest < Test::Unit::TestCase


def setup

  begin 
    require 'redland'
  rescue
    raise "Failed to find Redland library. Aborting RedRuby tests."
  end

end


def test_parse_file    
  uri_string='file:danbri-foaf.rdf'
  uri_string='http://rdfweb.org/people/danbri/rdfweb/webwho.xrdf'
  uri_string=ARGV[0] if ARGV[0]
  parser_name='raptor'

  puts "Testing with uri: #{uri_string}"

  world=Redland::librdf_new_world
  Redland::librdf_world_open world

  storage=Redland::librdf_new_storage world, "hashes", "test", "new='yes',hash-type='bdb',dir='.'"
  raise "Failed to create RDF storage" if !storage
  assert storage != nil, "librdf_new_storage world shouldn't return nil"


  model=Redland::librdf_new_model world, storage, ""
  if !model then
    Redland::librdf_free_storage storage
    raise "Failed to create RDF model"
  end
  assert model != nil, "librdf_new_model shouldn't return nil"

  parser=Redland::librdf_new_parser world, parser_name, "", nil
  if !parser then
    Redland::librdf_free_model model
    Redland::librdf_free_storage storage
    raise "Failed to create RDF parser"
  end
  
  assert parser != nil, "Should be able to get a parser (parser name: #{parser_name})"

  uri=Redland::librdf_new_uri world, uri_string

  stream=Redland::librdf_parser_parse_as_stream parser, uri, uri

  count=0
  while Redland::librdf_stream_end(stream) == 0
    statement=Redland::librdf_stream_get_object stream
    Redland::librdf_model_add_statement model, statement
    puts "found statement: #{Redland::librdf_statement_to_string statement}"
    count=count+1
    Redland::librdf_stream_next stream
  end

  Redland::librdf_free_stream stream

  puts "Parsing added #{count} statements"

  Redland::librdf_free_parser parser


 
  db=Graph.new([])
  puts "Printing all statements"
  stream=Redland::librdf_model_serialize model
  results=[]
  while Redland::librdf_stream_end(stream) == 0
    statement=Redland::librdf_stream_get_object stream
    puts "Statement: #{Redland::librdf_statement_to_string statement}"
    results.push(Redland::librdf_statement_to_string(statement))

	s = Redland::librdf_node_to_string(Redland::librdf_statement_get_subject(statement))
	p = Redland::librdf_node_to_string(Redland::librdf_statement_get_predicate(statement))
	o = Redland::librdf_node_to_string(Redland::librdf_statement_get_object(statement))
	st=Statement.new(s,p,o)
	db.tell(st)	
 
    Redland::librdf_stream_next stream
  end
  assert results.size>1, "Expected some statements"
  

  nt=db.toNtriples
  puts "Ntriples: #{nt}"
  assert(nt.size>50, "expected some ntriples")    


  Redland::librdf_free_stream stream
  Redland::librdf_free_model model
  Redland::librdf_free_storage storage
  Redland::librdf_free_world world

end

end
