package page.image;

import java.awt.image.BufferedImage;
import java.io.IOException;

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.*;

import page.tools.entity.User;

public class SetCookie implements HTTPResponder {
    
    public Object respond(HTTPHandler conn) throws IOException {
        
        // Obtain requested counter properties
        FormData formData = conn.getRequest().getFormData();
        if (formData != null) {
            String userID = formData.getFirst("userID");
            if (userID == null) {
                throw new HTTPException(500, "UserID not specified");
            }
            User u = User.getUserById(userID);
            if (u == null) {
                throw new HTTPException(500, "UserID specified could not be found");
            }
            String requestAddress = (String) u.get("lastRequestAddress");
            if (!conn.getSourceAddress().equals(requestAddress)) {
                throw new HTTPException(500, "Cookie can only be issued to same source IP");
            }
            String sessionAuth = (String) u.get("sessionAuth");
            if (sessionAuth == null) {
                throw new HTTPException(500, "User is not signed in");
            }                  
            // Implant the cookie data for the user
            HTTPHeaders responseHeaders = conn.getResponse().getHeaders();
            responseHeaders.set("userID", u.getId());
            responseHeaders.set("sessionAuth", sessionAuth);
        }
        
        // Render the text onto an image
        BufferedImage image = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB);
        image.setRGB(0, 0, 0xFFFFFFFF);

        return image;
    }
}
