package page.example;

import java.io.File;

import org.wikiwebserver.core.WareHouse;
import org.wikiwebserver.handler.http.HTTPException;
import org.wikiwebserver.handler.http.interfaces.HTTPResponder;
import page.config.SiteTemplatedPage;


public class ShowImages extends SiteTemplatedPage implements HTTPResponder {
	
    public void generate() throws HTTPException {
       
        // Process form data to find path
        if (getFormData() != null) {
            String path = getFormData().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.");
                }
                
                append("<h1>Showing images in " + dir + "</h1>");
                File[] files = dir.listFiles();
                for (File file : files) {
                    String type = WareHouse.getContentType(file.toString());
                    if (type != null && type.startsWith("image")) {
                        append(image(WareHouse.getUrlPathForFile(file), file.getName()));
                    }
                }
            }
            else throw new HTTPException(500, "Path parameter not found.");
        }
        else throw new HTTPException(500, "Path parameter required.");

    }
}
