/*
 * StoresHandler.java
 *
 * Created on 10 de agosto de 2004, 18:00
 */

package com.fenalco.servlets.shopkeeper;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.fenalco.entities.DataAccess;
import com.fenalco.entities.Log;
import com.fenalco.entities.Store;
import com.fenalco.entities.User;
import com.fenalco.utilities.MessageBuilder;
import com.fenalco.utilities.database.Transaction;

/**
 * Este servlet se encarga de realizar las operaciones de actualización,
 * borrado, y creacion de establecimientos propios del minorista de acuerdo con
 * el valor del parámetro <CODE>operationType</CODE>
 * 
 * @author Mario Linares Vásquez
 */
public class StoresHandler extends HttpServlet
{

	/**
	 * Inicializa el servlet.
	 * 
	 * @param config
	 * @throws ServletException
	 */
	public void init( ServletConfig config ) throws ServletException
	{
		super.init(config);

	}

	/**
	 * Destructor de servlet.
	 */
	public void destroy( )
	{

	}

	/**
	 * Procesa las solicitudes para los métodos HTTP <code>GET</code> y
	 * <code>POST</code>. Este método se encarga de ejecutar la operación
	 * seleccionada sobre los establecimientos de acuerdo con el valor del
	 * parámetro <CODE>operationType</CODE>: - operationType = new invoca la
	 * función <CODE>newStore</CODE> con el <CODE>request</CODE> como
	 * parámetro - operationType = update invoca la función <CODE>update
	 * </CODE> con el <CODE>request</CODE> y el parámetro <CODE>storeId
	 * </CODE>- operationType = delete invoca la función <CODE>delete</CODE>
	 * con el parámetro <CODE>storeId</CODE> El flujo se redirecciona al
	 * servlet misestablecimientos
	 * 
	 * @param request
	 *            servlet request
	 * @param response
	 *            servlet response
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void processRequest( HttpServletRequest request,
			HttpServletResponse response ) throws ServletException, IOException
	{
		String url = "/minorista/misestablecimientos";
		String message = "";
        HttpSession session = request.getSession( false );

	    try
	    {
	        if( session != null && ( User )session.getAttribute( "user" ) != null && ( ( User )session.getAttribute( "user" ) ).getRoleId() == 3 )
			{
	
				String operation = request.getParameter("operationType");
	
				if( operation.equals("new") )
				{
					Transaction transaction = new Transaction();
					Store store = new Store();
					String GLN = request.getParameter("GLN");
	
					if( !DataAccess.existGLN(GLN) )
					{
	
						this.preTransaction(request, transaction, store);
						store.saveData(transaction);
						transaction.execute();
						
						// guardo el registro de nuevo establecimiento en el Log
	                    try
	                    {
	                        Transaction t = new Transaction( );
	                        Log l = new Log( );
							User user = ( User )session.getAttribute( "user" );
	                        String userId = user.getLogin();
	                        String numberId = user.getIdentificationNumber();
	                        String externalUser = "";
	                        User callcenter = ( User )session.getAttribute( "callcenter" );
	                        String description = "Creación del establecimiento " + store.getName();
	                        if( callcenter != null )
	                        {
	                            externalUser = callcenter.getLogin();
	                        }
							l.saveData(userId, numberId, 12, description, externalUser, t );
	                        t.execute();
	                    }
	                    catch( Exception ex )
	                    {
	                        System.out.println( "Error guardando el Log." );
	                    }
	
					}
					else
					{
						message = MessageBuilder.buildMessage(22);
					}
				}
				else
					if( operation.equals("delete") )
					{
						String[] items = request.getParameterValues("item");
						if( items != null )
						{
							Transaction transaction = new Transaction();
							boolean flag = true;
							for( int i = 0; i < items.length; i++ )
							{
								Store store = new Store(Integer.parseInt(items[i]));
								if( store.delete(transaction) == false )
								{
									flag = false;
									message = "\\n - " + store.getName();
								}
								else
								{
									// guardo el registro de borrado de establecimiento en el Log
				                    try
				                    {
				                        Transaction t = new Transaction( );
				                        Log l = new Log( );
										User user = ( User )session.getAttribute( "user" );
				                        String userId = user.getLogin();
				                        String numberId = user.getIdentificationNumber();
				                        String externalUser = "";
				                        User callcenter = ( User )session.getAttribute( "callcenter" );
				                        String description = "Eliminación del establecimiento " + store.getName();
				                        if( callcenter != null )
				                        {
				                            externalUser = callcenter.getLogin();
				                        }
										l.saveData(userId, numberId, 14, description, externalUser, t );
				                        t.execute();
				                    }
				                    catch( Exception ex )
				                    {
				                        System.out.println( "Error guardando el Log." );
				                    }
									
								}
							}
							if( flag == false )
							{
	
								message = "Los siguientes establecimientos no fueron borrados porque tienen pedidos asociados: "
										+ message;
								request.setAttribute("error", "delete");
							}
	
							transaction.execute();
						}
					}
					else
						if( operation.equals("update") )
						{
							int id = Integer.parseInt(request.getParameter("id"));
							Transaction transaction = new Transaction();
							Store store = new Store(id);
							this.preTransaction(request, transaction, store);
							store.update(transaction);
							transaction.execute();
							
		                    try
		                    {
		                        Transaction t = new Transaction( );
		                        Log l = new Log( );
								User user = ( User )session.getAttribute( "user" );
		                        String userId = user.getLogin();
		                        String numberId = user.getIdentificationNumber();
		                        String externalUser = "";
		                        User callcenter = ( User )session.getAttribute( "callcenter" );
		                        String description = "Modificación del establecimiento " + store.getName();
		                        if( callcenter != null )
		                        {
		                            externalUser = callcenter.getLogin();
		                        }
								l.saveData(userId, numberId, 13, description, externalUser, t );
		                        t.execute();
		                    }
		                    catch( Exception ex )
		                    {
		                        System.out.println( "Error guardando el Log." );
		                    }
							
						}
			}
			else
			{
				message = MessageBuilder.buildMessage(15);
				url = "/index.jsp";
			}
	    }
	    catch( Exception e )
	    {
	        url="/logout";
	        message = MessageBuilder.buildMessage(15);
	    }

		//        System.out.println("el mensaje-->"+message);
		request.setAttribute("message", message);
		RequestDispatcher dispatcher = getServletContext()
				.getRequestDispatcher(url);
		dispatcher.forward(request, response);

	}

	/**
	 * Procesa el método HTTP <code>GET</code>.
	 * 
	 * @param request
	 *            servlet request
	 * @param response
	 *            servlet response
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void doGet( HttpServletRequest request,
			HttpServletResponse response ) throws ServletException, IOException
	{
		processRequest(request, response);
	}

	/**
	 * Procesa el método HTTP <code>POST</code>.
	 * 
	 * @param request
	 *            servlet request
	 * @param response
	 *            servlet response
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void doPost( HttpServletRequest request,
			HttpServletResponse response ) throws ServletException, IOException
	{
		processRequest(request, response);
	}

	/**
	 * Retorna una breve descripción de el servlet.
	 * 
	 * @return
	 */
	public String getServletInfo( )
	{
		return "Short description";
	}

	public void preTransaction( HttpServletRequest request,
			Transaction transaction, Store store )
	{

		int companyId = ((User) request.getSession().getAttribute("user"))
				.getCompanyId();

		String name = request.getParameter("name");
		String GLN = request.getParameter("GLN");
		String address = request.getParameter("address");
		String stratum = request.getParameter("stratum");
		String street = request.getParameter("street");
		String avenue = request.getParameter("avenue");
		String avenueOrientation = request.getParameter("avenueOrientation");
		String streetOrientation = request.getParameter("streetOrientation");

		String phoneNumber1 = request.getParameter("phoneNumber1");
		String phoneNumber2 = request.getParameter("phoneNumber2");
		String contact1 = request.getParameter("contact1");
		String contact2 = request.getParameter("contact2");

		String storeArea = request.getParameter("storeArea");
		String paymentPoints = request.getParameter("paymentPoints");
		String wareHouseArea = request.getParameter("wareHouseArea");

		String neighbourhood = request.getParameter("neighbourhood");

		if( phoneNumber2.length() == 0 )
		{
			phoneNumber2 = "0";
		}

		if( street.length() == 0 )
		{
			street = "0";
		}

		if( avenue.length() == 0 )
		{
			avenue = "0";
		}

		if( GLN.length() == 0 )
		{
			GLN = "0";
		}

		if( wareHouseArea.length() == 0 )
		{
			wareHouseArea = "0";
		}

		store.setAddress(address);
		store.setAvenue(Integer.parseInt(avenue));
		store.setAvenueOrientation(avenueOrientation);
		store.setStreet(Integer.parseInt(street));
		store.setStreetOrientation(streetOrientation);
		store.setCompanyId(companyId);
		store.setContact1(contact1);
		store.setContact2(contact2);
		store.setGln(GLN);
		store.setStratum(Integer.parseInt(stratum));
		store.setName(name);
		store.setNeighbourhood(Integer.parseInt(neighbourhood));
		store.setPayPlaces(Integer.parseInt(paymentPoints));
		store.setPhoneNumber1(phoneNumber1);
		store.setPhoneNumber2(phoneNumber2);
		store.setStoreArea(Double.parseDouble(storeArea));
		store.setStreet(Integer.parseInt(street));
		store.setStreetOrientation(streetOrientation);
		store.setWareHouseArea(Double.parseDouble(wareHouseArea));

	}

}