# -*- ruby -*-
# This is a test script for xpath.
# Note that this is not W3C XPath!

require 'xtemplate'

$data = {
  'members' => {
    'man' => [
      {'@uid' => 1, 'name' => 'name1', 'age' => 20},
      {'@uid' => 2, 'name' => 'name2', 'age' => 21},
      {'@uid' => 3, 'name' => 'name3', 'age' => 22},
    ],
    'woman' => [
      {'@uid' => 4, 'name' => 'name4', 'age' => 20},
      {'@uid' => 5, 'name' => 'name5', 'age' => 21},
      {'@uid' => 6, 'name' => 'name6', 'age' => 22},
    ]
  },
  'others' => [
    {'@uid' => 10, 'name' => 'name10'},
    {'@uid' => 11, 'name' => 'name11'},
  ]
}

include XTemplate
include XPath

def x(path)
  XTemplate::XPath::xpath(path,$data)
end

def test(path, val)
  if( x(path) == val )
    print("#{path}: ok\n")
  else
    print("#{path}: fail\n")
  end
end


test("/members/man", $data['members']['man'])
test("/members/woman|/members/man", $data['members']['woman'] + $data['members']['man'])
test("/members/man[0,2]", $data['members']['man'][0,2])
test("/members/man[0,2]/name", $data['members']['man'][0,2].collect{|x| x['name']})
test("/members/man[0..1]/name", $data['members']['man'][0..1].collect{|x| x['name']})
test("/members/man/@uid", $data['members']['man'].collect{|x| x['@uid']})
test("/members/*/@uid", x("/members/man/@uid") + x("/members/woman/@uid"))
test("/**/@uid", x("/*/@uid") + x("/*/*/@uid"))

# age is an integer value in given data. we don't need to convert it.
test("/**/man[int(age)>20]", x("/**/man").select{|n| n.is_a?(Hash) && n['age']>20})
test("/**[age and age>20]", x("/**").select{|n| n.is_a?(Hash) && n['age'] && n['age']>20})
test("/**[name =~ /1/]",  x("/**").select{|n| n.is_a?(Hash) && n['name'] =~ /1/ })
test("/**[name = 'name10']",  x("/**").select{|n| n.is_a?(Hash) && n['name'] == 'name10' })

test("/members/./man/.", x("/members/man"))
test("/members/man[0]/../woman/name", x("/members/woman/name"))

test("{time(%Y%m%d)}", [Time.now.strftime("%Y%m%d")])
test("//man{time(%Y,time)}", x("//man").collect{|d| d['time'] = Time.now.strftime("%Y"); d})

test("//man{dump()}", [XMLDocument.new(x("//man")).to_s])
test("//man{dump();sanitize()}", [sanitize(String.new(XMLDocument.new(x("//man")).to_s))])
test("//man{dump();sanitize();unsanitize()}", [XMLDocument.new(x("//man")).to_s])
