package com.etherios.gae.connector.tank;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.etherios.gae.connector.tank.datastore.UserData;
import com.etherios.gae.connector.tank.datastore.UserDataUtils;

@SuppressWarnings("serial")
public class DevicesServlet extends BaseServlet {
	/*
	 * (non-Javadoc)
	 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
	throws ServletException, IOException {
		clearErrorMessage();
		
		UserData user = getUserFromSession(req);
		if (user == null) {
			req.setAttribute("error", errorMessage);
			loginDispatcher.forward(req, resp);
			return;
		}
		
		devicesDispatcher.forward(req, resp);
	}
	
	/*
	 * (non-Javadoc)
	 * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		UserData user = getUserFromSession(req);
		if (user == null) {
			req.setAttribute("error", errorMessage);
			loginDispatcher.forward(req, resp);
			return;
		}
		
		String selectedDevice = (String) req.getParameter("selectedDevice");
		String latitude = (String) req.getParameter("latitude");
		String longitude = (String) req.getParameter("longitude");
		if (selectedDevice == null) {
			req.setAttribute("error", "Selected device cannot be null");
			devicesDispatcher.forward(req, resp);
			return;
		}
		
		UserDataUtils.setSelectedDevice(user.getUserID(), selectedDevice);
		UserDataUtils.setLatitude(user.getUserID(), latitude);
		UserDataUtils.setLongitude(user.getUserID(), longitude);
		resp.sendRedirect(PAGE_TANK_SERVLET);
	}
}
