/**
 * @license
 * Copyright 2017 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

package foam.nanos.http;

import foam.core.*;
import foam.nanos.http.ProxyWebAgent;
import foam.nanos.http.WebAgent;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;

public class RefreshWebAgent
  extends ProxyWebAgent
{
  public RefreshWebAgent(WebAgent delegate) {
    setDelegate(delegate);
  }

  public void execute(X x) {
    final PrintWriter out = (PrintWriter) x.get(PrintWriter.class);
    HttpServletRequest req     = (HttpServletRequest) x.get(HttpServletRequest.class);
    String json = req.getParameter("refresh");

    out.println("<pre>");
    out.println("<form>");
    out.println("<label>Refresh Rate (sec):</label>");
    out.println("<input name=\"refresh\" type=\"number\" value=\"refresh\" style=\"width:150px;display:inline-block;\"></input>");
    out.println("<button type=submit style=\"display:inline-block;margin-top:10px;\";>Set Refresh</button>");
    out.println("</form>");
    out.println("</pre>");
    
    getDelegate().execute(x);

    if( json != null || !"".equals(json) ){
      int refresh = Integer.parseInt(json);
      out.println("<script>");
      out.println("setTimeout(function(){ window.location.href = window.location.href; }, "+ refresh * 1000 + "); ");
      out.println("</script>");
    }
  }
}
@@ -479,14 +479,8 @@
     
-final 
 Prin
@@ -491,12 +491,20 @@
 ter 
+       
 out 
+ 
 = (P
@@ -569,19 +569,16 @@
 st req  
-   
 = (HttpS
@@ -636,16 +636,28 @@
  String 
+            
 json = r
@@ -688,35 +688,105 @@
 %22);%0A
-%0A
     
-out.println(%22%3Cpre%3E%22
+int                refresh = json == null %7C%7C %22%22.equals(json) ? -1 : Integer.parseInt(json
 );%0A
+%0A
     
@@ -928,23 +928,58 @@
 value=%5C%22
+%22 + ( 
 refresh
+ == -1 ? %22%22 : %22%22+refresh) + %22
 %5C%22 style
@@ -992,9 +992,9 @@
 th:1
-5
+0
 0px;
@@ -1171,39 +1171,8 @@
 %22);%0A
-    out.println(%22%3C/pre%3E%22);%0A    
 %0A   
@@ -1209,55 +1209,10 @@
   if
+ 
 (
- json != null %7C%7C !%22%22.equals(json) )%7B%0A      int
  ref
@@ -1220,33 +1220,17 @@
 esh 
+!
 = 
-Integer.parseInt(json);
+-1 ) %7B
 %0A   
@@ -1418,8 +1418,9 @@
  %7D%0A  %7D%0A%7D
+%0A

Update RefreshWebAgent.