open Galapi

(* 
   Example 1 

   Build a query context from a file.
   Load a document.
   Add a global variable to query context, bound to the loaded document.
   Evaluate a query contained in a string.
   Serialize result to standard output

*)
let output_result res = 
  match res with 
  | None -> ()
  | Some res' -> serialize_to_formatter Format.std_formatter res'

let example1 mod_ctxt =

  try
    (* Evaluate global variables *)
    let mod_ctxt' = Galapi.eval_global_variables mod_ctxt in 
    let res = eval_statement_from_string mod_ctxt' "for $s in $report//section[section.title = \"Procedure\"] return ($s//incision)[2]/instrument" in  
    output_result res
  with

    (* Any errors raised by Galax are printed to stderr *)
  | exn -> Error.printf_error "Example 1:" exn

(* 
   Example 2

   Build a query context from a file.
   Load a document.
   Evaluate a query contained in a file.
   Serialize result to standard output.

*)
let example2 mod_ctxt =

  try
    (* Load main module *)
    let (mod_ctxt'', stmts) = Galapi.import_main_module mod_ctxt "seq.xq" in
    (* Evaluate global variables *)
    let mod_ctxt''' = Galapi.eval_global_variables mod_ctxt'' in 
    List.iter 
      (fun stmt -> 
	output_result (eval_statement mod_ctxt''' stmt)) 
      stmts
  with
    (* Any errors raised by Galax are printed to stderr *)
  | exn -> Error.printf_error "Example 2" exn

(* 
   Example 3

   Build a query context from a file.
   Create some XML values. 
   Evaluate a query function contained in the query context by
   applying to XML values.
   Serialize result to a string & print. 

*)
let example3 mod_ctxt xmldoc =
  try
    (* Load main module *)
    let mod_ctxt'' = Galapi.import_library_module mod_ctxt "xq-example1.xq" in
    (* Evaluate global variables *)
    let mod_ctxt''' = Galapi.eval_global_variables mod_ctxt'' in 
    let xmlstr = xs_string "a string" in
    let xmlint = xs_int 12 in
    let res = eval_query_function mod_ctxt''' "test2" [[xmlint]; [xmlstr]] in
    (* Serialize the result to a string *)
    print_string(serialize_to_string res) 
  with
    (* Any errors raised by Galax are printed to stderr *)
  | exn -> Error.printf_error "Example 3" exn


let _ =
  try 
    let pc = Galapi.default_processing_context() in
    let mod_ctxt = Galapi.load_standard_library pc in
    let mod_ctxt' = import_library_module mod_ctxt "seq_context.xq" in
    let xmldoc = load_document "report.xml" in
    Conf.optim := false;
    example1 mod_ctxt';
    example2 mod_ctxt';
    example3 mod_ctxt' xmldoc;
  with
  | exn -> Error.printf_error "" exn

