package com.etherios.gae.connector.tank;

import java.io.IOException;
import java.util.ArrayList;

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

import com.digi.connector.client.CloudConnection;
import com.digi.connector.client.models.CloudDevice;
import com.etherios.gae.connector.tank.datastore.UserData;
import com.etherios.gae.connector.tank.datastore.UserDataUtils;

@SuppressWarnings("serial")
public class LoginServlet extends BaseServlet {
	// Constants.
	public static final String HTTP_PREFIX = "http://";
	
	/*
	 * (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();
		
		loginDispatcher.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 {
		clearErrorMessage();
		
		// We received an error, redirect to the get method setting the received error.
		if (req.getParameter("error") != null) {
			req.setAttribute("error", req.getParameter("error"));
			doGet(req, resp);
			return;
		}
		
		// Get the User and Password.
		String username = req.getParameter("username");
		String password = req.getParameter("password");
		
		// Get the server to connect to.
		String server = req.getParameter("servers-combo");
		
		if (username == null ||username.length() == 0 || 
				password == null || password.length() == 0) {
			errorMessage = ERROR_EMPTY_USER;
			
			req.setAttribute("error", ERROR_EMPTY_USER);
			loginDispatcher.forward(req, resp);
			
			//resp.sendRedirect("/login.jsp?error=" + errorMessage);
			return;
		}
		
		// Remove the (US)/(EU) suffix.
		if (server.contains(" ")) {
			int blankSpaceInd = server.indexOf(" ");
			server = server.substring(0, blankSpaceInd);
		}
		
		// Add the HTTP prefix to the server.
		if (!server.startsWith(HTTP_PREFIX))
			server = HTTP_PREFIX + server;
		
		// Generate the user ID.
		String userID = username + server;
		
		// Create the CloudConnection object with the provided user, password and server.
		CloudConnection cloudConnection = new CloudConnection(username, password, server);
		// Verify if the account is valid.
		ArrayList<CloudDevice> devicesList = cloudConnection.getDevices(true);
		if (devicesList == null) {
			errorMessage = ERROR_INVALID_USER;
			
			req.setAttribute("error", ERROR_INVALID_USER);
			loginDispatcher.forward(req, resp);
			
			//resp.sendRedirect("/login.jsp?error=" + errorMessage);
			return;
		}
		
		// Add or update the user in the Application Data Store.
		UserData user = UserDataUtils.getUserFromDataStore(userID);
		if (user == null) {
			user = new UserData(username, password, server);
			UserDataUtils.addUserToDataStore(user);
		} else {
			// Check if the password has changed, in that case update it.
			if (!user.getPassword().equals(password))
				UserDataUtils.updateUserPassword(userID, password);
			
			// Update the server for this user. 
			if (user.getServer() == null || 
					!user.getServer().equals(server))
				UserDataUtils.setServer(userID, server);
		}
		
		HttpSession session = req.getSession(true);
		session.setAttribute(SESSION_USER, user.getUser());
		session.setAttribute(SESSION_USER_ID, user.getUserID());
		
		resp.sendRedirect(PAGE_DEVICES_SERVLET);
	}
}
