package jp.sourceforge.tamanegisoul.er;

import java.io.IOException;
import java.util.Date;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.Text;

@SuppressWarnings("serial")
public class ErrorReportServlet extends HttpServlet {
    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        doService(req, resp);
    }

    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        doService(req, resp);
    }

    public void doService(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // if ("メザマシ！".equals(req.getParameter("appName"))) {
        PersistenceManager pm = PMF.get().getPersistenceManager();
        try {
            if (req.getParameter("device") != null) {
                // 端末から
                pm.makePersistent(new ErrorReport(req.getParameter("device"), req.getParameter("model"), req.getParameter("sdkVersion"), req.getParameter("appName"), req.getParameter("appVersion"), new Text(req.getParameter("message")), new Date(), Boolean.FALSE));
            } else {
                // Webから
                ErrorReport obj = pm.getObjectById(ErrorReport.class, Long.valueOf(req.getParameter("id")));
                if ("fixed".equals(req.getParameter("fixed"))) {
                    obj.setFixed(Boolean.TRUE);
                } else {
                    obj.setFixed(Boolean.FALSE);
                }
            }
        } finally {
            pm.close();
        }
        // }
        if (req.getParameterMap().keySet().contains("devide")) {
            // 端末から
            resp.setContentType("text/plain");
            resp.getWriter().println("success");
        } else {
            // Webから
            resp.sendRedirect("/index.jsp");
        }
    }
}
