package org.netmelody.cieye.server.response;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ResourceBundle;

import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.netmelody.cieye.server.PictureFetcher;
import org.simpleframework.http.Response;

public final class PictureResponder implements CiEyeResponder {

    private static final Log LOG = LogFactory.getLog(PictureResponder.class);
    private static final ResourceBundle MIME_TYPES = ResourceBundle.getBundle(FileResponder.class.getName());
    
    private final String name;
    private final String extension;
    private final PictureFetcher state;

    public PictureResponder(PictureFetcher state, String name) {
        this.state = state;
        this.name = name;
        this.extension = name.substring(name.lastIndexOf('.') + 1);
        LOG.info(name);
    }

    @Override
    public void writeTo(Response response) throws IOException {
        FileInputStream picture = null;
        OutputStream body = null;
        try {
            body = response.getOutputStream();
            File file = state.getPictureResource(name);
            picture = new FileInputStream(file);
            long time = System.currentTimeMillis();
            response.set("Content-Type", contentTypeOf(extension));
            response.set("Server", "CiEye/1.0 (Simple 4.0)");
            response.setDate("Date", time);
            response.setDate("Last-Modified", file.lastModified());
            IOUtils.copy(picture, body);
        }
        catch (IOException e) {
            LOG.error("Failed to get picture " + this.name, e);
            response.setCode(500);
        }
        finally {
            IOUtils.closeQuietly(picture);
            IOUtils.closeQuietly(body);
        }
    }

    private static String contentTypeOf(String extension) {
        return MIME_TYPES.getString(extension);
    }
}


@@ -1204,24 +1204,30 @@
             
+final 
 File file = 
@@ -1311,60 +1311,8 @@
 e);%0A
-            long time = System.currentTimeMillis();%0A
     
@@ -1403,337 +1403,90 @@
 .set
-(%22Server%22, %22CiEye/1.0 (Simple 4.0)%22);%0A            response.setDate(%22Date%22, time);%0A            response.setDate(%22Last-Modified%22, file.lastModified());%0A            IOUtils.copy(picture, body);%0A        %7D%0A        catch (IOException e) %7B%0A            LOG.error(%22Failed to get picture %22 + this.name, e);%0A            response.setCode(500
+Date(%22Last-Modified%22, file.lastModified());%0A            IOUtils.copy(picture, body
 );%0A 

simplify PictureResponder