package pl.helion.j2mepp.zdalnakamera.serwlety;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class ZdalnaKameraSerwlet extends HttpServlet {
   
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */

    private Map<String, byte[]> dane;
    private Random rand = new Random(new Date().getTime());

    private String wygenerujIWstawSID() {
        StringBuilder sb = new StringBuilder();
        String s = null;
        boolean zakonczono = false;
        do {
            for (int i=0;i<15;i++) {
                int n = rand.nextInt(25)+97;
                sb.append((char)n);
            }
            s = sb.toString();
            sb = new StringBuilder();
            synchronized(dane) {
                if (!this.dane.containsKey(s)) {
                    this.dane.put(s, new byte[0]);
                    zakonczono = true;
                }
            }
        } while (!zakonczono);
        return s;
    }

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        this.dane = (Map<String, byte[]>)this.getServletContext().getAttribute("dane");
        try {
            String akcja = request.getParameter("akcja");
            if (akcja.equals("generujSID"))
                this.wyslijSID(response);
            else {
                String sid = request.getParameter("SID");
                if (this.dane.containsKey(sid)) {
                    if (akcja.equals("pobierzZdjecie"))
                        this.pobierzZdjecie(response, sid);
                    else
                    if (akcja.equals("wyslijZdjecie")) 
                        this.wyslijZdjecie(request, sid);
                    else
                    if (akcja.equals("wyloguj"))
                        dane.remove(sid);
                }
            }
        } finally { 
            
        }
    }

    private void wyslijSID(HttpServletResponse response) throws IOException {
        response.setContentType("text/plain;charset=UTF-8");
        String sid = this.wygenerujIWstawSID();
        PrintWriter out = response.getWriter();
        out.print(sid);
        out.close();
    }

    private void pobierzZdjecie(HttpServletResponse response, String sid) throws IOException {
        byte[] bufor = this.dane.get(sid);
        response.setContentLength(bufor.length);
        OutputStream os = response.getOutputStream();
        os.write(bufor);
        os.close();
    }

    private void wyslijZdjecie(HttpServletRequest request, String sid) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        try {
            List items = upload.parseRequest(request);
            Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (!item.isFormField())
                    dane.put(sid, item.get());
            }
        } catch (Exception fue) {
            fue.printStackTrace();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
