package page.com.googleoids;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

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.HTTPHeaders;
import org.wikiwebserver.handler.http.interfaces.CacheableHTTPResponse;
import org.wikiwebserver.handler.http.interfaces.HTTPResponder;

public class GoogleProxy implements HTTPResponder, CacheableHTTPResponse {
    
    private String pathString;
    

    public void init(HTTPHandler conn) throws IOException {
        FormData formData = conn.getRequest().getFormData();
        if (formData == null) {
            throw new HTTPException(500, "No form data sent");
        }
        this.pathString = formData.getFirst("path");
        if (pathString == null) {
            throw new HTTPException(500, "Path not specified");
        }
    }    

    public Object respond(HTTPHandler conn) throws IOException {

       
        HttpURLConnection googleConn = null;
        InputStream in = null;
        try {
            URL url = new URL("http://images.google.com" + this.pathString);  
            googleConn = (HttpURLConnection) url.openConnection();          
        
            String contentType = googleConn.getContentType();
            int contentLength = googleConn.getContentLength();
        
            in = googleConn.getInputStream(); 
            
            HTTPHeaders headers = conn.getResponse().getHeaders();        
            headers.set("Content-Type", contentType);
            if (contentLength > -1) {
                headers.set("Content-Length", String.valueOf(contentLength));
            }
            
            // Stream the response
            WareHouse.proxyStream(in, conn.getOutputStream());
            
        } catch (Exception ex) {
            if (googleConn != null) {
                conn.getResponse().setCode(googleConn.getResponseCode());
                conn.getResponse().setInfo(googleConn.getResponseMessage());
                WareHouse.proxyStream(googleConn.getErrorStream(), conn.getOutputStream());
            }
        } finally {
            if (in != null) in.close();
        }
        
        return null;
    }

    public String getCacheKey() {
        return pathString;
    }

    public long getExpireTime() {
        return System.currentTimeMillis() + 7 * 24 * 60 * 60 * 1000;
    }
  
}
