package page.tools.management;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import org.wikiwebserver.core.WareHouse;
import org.wikiwebserver.core.WikiMap;
import org.wikiwebserver.handler.http.*;
import org.wikiwebserver.handler.http.interfaces.HTTPResponder;

import page.config.SiteTemplatedPage;
import page.tools.entity.User;

public class FileUpload implements HTTPResponder {
	
    public Object respond(HTTPHandler conn) throws IOException {
    	
    	throw new HTTPException(403, "Sorry. File upload was disabled due to abuse.");
        
    	/*
        HTTPInputStream reader = conn.getInputStream();
        FormData formData = conn.getRequest().getFormData();  
        List<File> uploadedFiles = new ArrayList<File>();
        
        User u = User.getUser(conn.getRequest());
        if (u == null) {
            throw new HTTPException(403, "User not logged in.");
        }
        
        StringBuilder debugger = new StringBuilder();
        
        String contentType = conn.getRequest().getHeaders().getFirst("Content-Type");
        if (contentType == null) {
            return getUploadForm();
        }
        else if (!contentType.contains("multipart/form-data")) {
            throw new HTTPException(500, "Multi-part upload task failed (bad content type)");
        }
        else {
            String uid = newUploadID();           
            
            try {
                debugger.append("Content-Type: " + contentType + "\r\n");
                String cls = conn.getRequest().getHeaders().getFirst("Content-Length");
                long contentLength = Integer.parseInt(cls);
                logStartUpload(uid, contentLength); 
                
                if (formData == null) {
                    formData = new FormData();
                }
                
                // Extract boundary from headers
                String boundary = null;
                String marker = "boundary=";
                int idx = contentType.indexOf(marker);
                boundary = contentType.substring(idx+marker.length());
                debugger.append("Boundary: " + boundary + "\r\n");
                
                String realBoundary = "\r\n--" + boundary;
                
                // Skip to first part
                reader.skipUntil(boundary + "\r\n");
                
                // Jump over boundary
                reader.skipBytes(boundary.length() + 2);            
                
                while (!Thread.currentThread().isInterrupted()) {
                    // Read headers
                    String headers = reader.readStringUntil("US-ASCII", "\r\n\r\n");
                    reader.skipBytes(4);
                    
                    // Extract content disposition from headers
                    debugger.append("Headers >" + headers + "<\r\n");
                    String contentDisposition = WareHouse.getBetween("Content-Disposition: ", null, headers);
                    debugger.append("Content-Disposition: " + contentDisposition + "\r\n");
                    
                    // Extract filename from content disposition
                    String name = WareHouse.getBetween("name=\"", "\"", contentDisposition);
                    String filename = WareHouse.getBetween("filename=\"", "\"", contentDisposition);
                    debugger.append("filename: " + filename + "\r\n");
                    
                    if (filename != null && filename.length() > 0) {
                        
                        // Fix windows slashes
                        filename = filename.replace('\\', '/');
                        
                        // IE sends full path, strip it
                        filename = new File(filename).getName();
                        String fid = newFileUploadID();
                        
                        File userFile = SiteTemplatedPage.getUserDir(u);
                        if (!userFile.exists()) userFile.mkdirs();
                                             
                        File file = new File(userFile, filename);
                        
                        // Stream data to local file
                        FileOutputStream out = null;
                        try {
                            logStartFileUpload(fid, file);
                            out = new FileOutputStream(file);
                            reader.streamUntil(realBoundary, out);
                            uploadedFiles.add(file);
                        } catch (Exception ex) {
                            ex.printStackTrace();
                            file.delete();
                            HTTPException httpe = new HTTPException(500, "Upload failed: " + file);
                            httpe.initCause(ex);
                            throw httpe;
                        } finally {
                            if (out != null) out.close();
                            logFinishFileUpload(fid, file);
                        }
                        
                    }
                    // This is not a file upload
                    else {
                        String value = reader.readStringUntil("US-ASCII", realBoundary);
                        if (name != null && value != null && value.length() > 0) {
                            formData.set(name, value);
                        }
                    }
                    
                    // Jump over boundary
                    reader.skipBytes(realBoundary.length());
                    
                    String cont = reader.readString("US-ASCII", 2);
                    
                    // Termination criteria (end of last part)
                    if (cont.equals("--")) break;
                }                
            } catch (Exception ex) {
                ex.printStackTrace();
                HTTPException httpe = new HTTPException(500, "Multi-part upload task failed (interrupted)");
                httpe.initCause(ex);
                throw httpe;             
            } 
            finally {
                logFinishUpload(uid); 
            }
        }
        
        //System.out.println(debugger.toString());        
        
        // Test form
        if (uploadedFiles.size() > 0) {
            if (formData != null) {
                String redirect = formData.getFirst("redirect");
                if (redirect != null && redirect.length() > 0) {
                    // This will also redirect the upload which is wrong
                    // throw new HTTPException(307, "Upload complete", redirect);
                    
                    StringBuilder redirector = new StringBuilder();
                    redirector.append("<script type='text/javascript'>\r\n" +
                                      "<!--\r\n" +
                                      "window.location = '" + redirect + "';\r\n" +
                                      "//-->\r\n" +
                                      "</script>"); 
                    
                    return redirector.toString();
                }   
            }
            conn.getResponse().getHeaders().set("Content-Type", "text/plain");
            return getUploadSummary(uploadedFiles.toArray(new File[uploadedFiles.size()]));
        }
        
        throw new HTTPException(500, "File upload failed");
    	 */
    }
    
    private String getUploadForm() {
        StringBuilder test = new StringBuilder();
        test.append("<form method='post' enctype='multipart/form-data'>");
        for (int i=0; i<5; i++) {
            test.append("<input type='file' name='file" + i + "'><br/>");
        }
        test.append("<input type='submit' value='Send'></form>");    
        return test.toString();
    }
    
    public static String getUploadSummary(File[] files) {
        if (files == null) return "";
        StringBuilder response = new StringBuilder();
        for (File file : files) {
            response.append(file.toString() + " ");
            response.append(file.length() + " bytes\r\n");
        }
        return response.toString();        
    }
    
    public static File[] getActiveFileUploads() {
        Collection<?> c = getData("FileUploads").values();
        if (c == null || c.size() == 0) return null;
        Iterator<?> it = c.iterator();
        File[] files = new File[c.size()];
        for (int i=0; i<files.length; i++) {
            files[i] = new File((String)it.next());
        }
        return files;
    }
    
    private static WikiMap getData(String name) {
        WikiMap map = WareHouse.getWikiMap(name);
        if (map == null) map = WareHouse.initWikiMap(name);
        return map;        
    }    
    
    private void logStartUpload(String id, long size) {
        getData("Uploads").put(id, size);
    }
    
    private void logFinishUpload(String id) {
        getData("Uploads").remove(id);
    } 
    
    private void logStartFileUpload(String id, File file) {
        getData("FileUploads").put(id, file.getPath());
    }
    
    private void logFinishFileUpload(String id, File file) {
        getData("FileUploads").remove(id);
    }    
    
    private static String newUploadID() {
        return newIdentity("Upload");
    } 
    
    private static String newFileUploadID() {
        return newIdentity("FileUpload");
    }      
    
    private static String newIdentity(String name) {
        return WareHouse.newIdentity("FileUpload");
    }     
}
