package page.example;

import java.io.File;

import org.wikiwebserver.core.WareHouse;
import org.wikiwebserver.handler.http.FormData;
import org.wikiwebserver.handler.http.HTTPException;
import org.wikiwebserver.handler.http.HTTPHandler;
import org.wikiwebserver.handler.http.interfaces.HTTPResponder;

public class ImageSlideShow implements HTTPResponder {
	
    public Object respond(HTTPHandler conn) throws HTTPException {
       
        // Process form data to find path
        FormData formData = conn.getRequest().getFormData();
        if (formData != null) {
            String path = formData.getFirst("path");
            if (path != null && path.length() > 1) {
                // file is relative
                String filePath = path.startsWith("/") ? path.substring(1) : path;
                File dir = new File(filePath);
                if (!dir.isDirectory()) {
                    throw new HTTPException(500, "Path to directory expected.");
                }
                
                StringBuilder script = new StringBuilder();
                
                script.append("<script type='text/javascript' src='http://slideshow.triptracker.net/slide.js'></script>" + LF);
                script.append("<script type='text/javascript'>" + LF + "<!--" + LF);
                script.append("var viewer = new PhotoViewer();" + LF);

                File[] files = dir.listFiles();
                for (File file : files) {
                    String type = WareHouse.getContentType(file.toString());
                    if (type != null && type.startsWith("image")) {
                        String url = WareHouse.getUrlPathForFile(file);
                        String resized = "/image/ImageResizer.class?s=1024&path=" + url;
                        script.append("viewer.add('" + resized + "','" + file.getName() + "');" + LF);
                    }
                }

               
                //script.append("viewer.setShadeColor('#237FBE');" + LF);
                script.append("viewer.disableEmailLink();" + LF);
                script.append("viewer.disablePhotoLink();" + LF);
                script.append("viewer.show(0);" + LF);      
                script.append("viewer.enableLoop();" + LF);  
                script.append("viewer.enableAutoPlay();" + LF);  

                script.append("-->" + LF + "</script>");
                
                return "<html><body>" + script.toString() + "</body></html>";
            }
            else throw new HTTPException(500, "Path parameter not found.");
        }
        else throw new HTTPException(500, "Path parameter required.");

    }
    
    private static final String LF = "\r\n";
}
