-module (demos_comet1).
-include_lib ("nitrogen_core/include/wf.hrl").

main() -> #template { file="./templates/demos46.html" }.
title() -> "Simple Comet".

headline() -> "Simple Comet".

left() -> 
        Nitrogen allows you to spawn a comet process in one line of
        code using the <code>wf:comet/1</code> function.  

        With comet, you can execute some task asynchronously, and then
        push the results to the browser as they are available.

        In this demo, a comet process simply increments a counter once
        per second.

right() -> 
    Body = [
        #span { text="Counter updated via Comet: " },
        #span { id=myCounter, text="-" }
    wf:comet(fun() -> background_update(myCounter, 1) end),

event(_) -> ok.

background_update(ControlID, Count) ->
    % Sleep for a second, then update

    % Update the control.
    wf:update(ControlID, wf:to_list(Count)),

    % wf:comet_flush() is only needed because we are looping. Otherwise,
    % we could just let the function complete.

  % Loop. This process will automatically be killed once the page stops
  % requesting the output that it generates.
  % Using ?MODULE before the function call will ensure that this process
  % survives code reloads.
    ?MODULE:background_update(ControlID, Count + 1).