open Safestd
open Safeapplets
open Safetk
open Safetkanim

open Tk
open Tkanim
open Document
open Viewers

open Capabilities
module Provide = struct
  let capabilities = Capabilities.get()
  end

module Net = Safeapplets.Retrieval(Provide)
open Net

let load_image w delay loop l =
  let rec animate = function
      [] -> if loop then animate l
  | url::rest ->
     (* Retrieve the image *)
     get_image url
       (* Continuation of image loading *)
       (function 
	 Still o -> 
	    if Winfo.exists w then begin
	      Label.configure w [o];
	      Timer.add delay (fun () -> animate rest);
	      ()
       	    end
	 | _ -> ())
  in
  animate l


(* The applet can be invoked with
<EMBED SRC="../applets/slide.cmo">
<PARAM NAME="function" VALUE=f>
<PARAM VALUE="url of some image">
...
</EMBED>
*)
let f w ctx =
  let l = Label.create w [Text "Slide Show"] in
    pack [l][];
    let delay = 
     try int_of_string (List.assoc "delay" ctx.viewer_params) with _ -> 3000
    and urls = ref [] in
       List.iter (function (name,value) when name = "url" ->
			      urls := Lexurl.make value :: !urls
			 | _ -> ())
		 ctx.viewer_params;
      load_image l delay false (List.rev !urls)

let loop w ctx =
  let l = Label.create w [Text "Looping Slide Show"] in
    pack [l][];
    let delay = 
     try int_of_string (List.assoc "delay" ctx.viewer_params) with _ -> 3000
    and urls = ref [] in
       List.iter (function (name,value) when name = "url" ->
			      urls := Lexurl.make value :: !urls
			 | _ -> ())
		 ctx.viewer_params;
      load_image l delay true (List.rev !urls)

(* Register the applet function. *)
let _ = Applets.register "f" f
let _ = Applets.register "loop" loop
