/*
 * CompanyListHandler.java
 *
 * Created on 10 de agosto de 2004, 18:20
 */

package com.fenalco.servlets.sysmanager;

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.Company;
import com.fenalco.entities.DataAccess;
import com.fenalco.entities.Log;
import com.fenalco.entities.Store;
import com.fenalco.entities.User;
import com.fenalco.entities.Supplier;
import com.fenalco.entities.ShopKeeper;
import com.fenalco.utilities.MessageBuilder;
import com.fenalco.utilities.database.Transaction;

/**
 * 
 * @author andres
 * @version
 */
public class CompanyListHandler extends HttpServlet
{

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

	}

	/**
	 * Destruye el servlet.
	 */
	public void destroy( )
	{

	}

	/**
	 * Procesa las peticiones de los mètodos HTTP <code>GET</code> y
	 * <code>POST</code>.
	 * 
	 * Recibe del request el parametro operationType
	 * 
	 * -Llama una determinada función dependiendo del valor de operationType
	 * 1)"changeState" updateCompany(request)
	 * 
	 * 2)"delete" deleteCompany(request)
	 * 
	 * -Redirecciona a listaempresas
	 * 
	 * @param request
	 *            peticiòn al servlet
	 * @param response
	 *            respuesta del servlet
	 */
	protected void processRequest( HttpServletRequest request,
			HttpServletResponse response ) throws ServletException, IOException{

            String url = "";
            String message = "";
            HttpSession session = request.getSession(false);
	    try{
	        if( session == null || ( User )session.getAttribute( "user" ) == null || ( ( User )session.getAttribute( "user" ) ).getRoleId() != 1 ){
                    url = "/index.jsp";
                    message = MessageBuilder.buildMessage(15);
                }else{
	
                    message = MessageBuilder.buildMessage(4);
                    String operationType = request.getParameter("operationType");
                    if( operationType.equals("changeStatus") ){
                        if( !updateCompany(request) ){
                                message = MessageBuilder.buildMessage(7);
                        }else{
                            Log log = new Log();
                            String userId = ((User) session.getAttribute("user")).getLogin();
                            String numberId = ((User) session.getAttribute("user")).getIdentificationNumber();
                            String description = "Empresa->"
                                            + request.getParameter("key")
                                            + ",Estado->"
                                            + request.getParameter("status"
                                            + request.getParameter("key"));
                            Transaction t = new Transaction();
                            log.saveData(userId, numberId, 23, description, "", t);
                            t.execute();
                        }
                        url = "/administrador/listaempresas";
                    
                    }else if( operationType.equals("delete") ){
                    
                            if( request.getParameter("item") != null ){
                                    if( !deleteCompany(request) ){
                                            message = MessageBuilder.buildMessage(8);
                                    }else{
                                            Log log = new Log();
                                            String userId = ((User) session.getAttribute("user")).getLogin();
                                            String numberId = ((User) session.getAttribute("user")).getIdentificationNumber();
                                            String description = "Empresa->"
                                                            + request.getParameter("key");
                                            Transaction t = new Transaction();
                                            log.saveData(userId, numberId, 19, description, "", t);
                                            t.execute();
                                    }
                            }else{
                                    message = "";
                            }
                            url = "/administrador/listaempresas";
                    
                    }else if( operationType.equals("updateStore") ){
                        
                        Store store = new Store(Integer.parseInt(request.getParameter("key")));
                        String gln = request.getParameter("gln");
                        
                        if( gln.equals(store.getGln()) || !DataAccess.existGLN(gln) ){
                        
                            if( !updateStore(request) ){
                                    message = MessageBuilder.buildMessage(7);
                                    url = "/administrador/verestablecimiento?key=" + request.getParameter("key");
                            }else{
                                /*Log log = new Log();
                                String userId = ((User) session.getAttribute("user")).getLogin();
                                String numberId = ((User) session.getAttribute("user")).getIdentificationNumber();
                                String description = "Establecimiento->"
                                                + request.getParameter("key")
                                                + ",Estado->"
                                                + request.getParameter("status"
                                                + request.getParameter("key"));
                                Transaction t = new Transaction();
                                log.saveData(userId, numberId, 23, description, "", t);
                                t.execute();*/
                                url = "/administrador/listaestablecimientos?key=" + store.getCompanyId();
                            }
                        }else{
                            message = "Error el GLN ya existe";
                            url = "/administrador/verestablecimiento?key=" + request.getParameter("key");
                        }
                        
                    }else if( operationType.equals("updateSupplier") ){

                        Supplier supplier = new Supplier(Integer.parseInt(request.getParameter("key")));
                        String gln = request.getParameter("gln");
                        
                        if( gln.equals(supplier.getGln()) || !DataAccess.existGLN(gln) ){
                        
                            if( !updateSupplier(request) ){
                                    message = MessageBuilder.buildMessage(7);
                                    url = "/administrador/actualizarempresas?key=" + request.getParameter("key") + "&operationType=updateSupplier";
                            }else{
                                /*Log log = new Log();
                                String userId = ((User) session.getAttribute("user")).getLogin();
                                String numberId = ((User) session.getAttribute("user")).getIdentificationNumber();
                                String description = "Establecimiento->"
                                                + request.getParameter("key")
                                                + ",Estado->"
                                                + request.getParameter("status"
                                                + request.getParameter("key"));
                                Transaction t = new Transaction();
                                log.saveData(userId, numberId, 23, description, "", t);
                                t.execute();*/
                                url = "/administrador/listaempresas?companyType=2";
                            }
                        }else{
                            message = "Error el GLN ya existe";
                            url = "/administrador/actualizarempresas?key=" + request.getParameter("key") + "&operationType=updateSupplier";
                        }
                        
                    }else if( operationType.equals("updateShopKeeper") ){

                        ShopKeeper shopKeeper = new ShopKeeper(Integer.parseInt(request.getParameter("key")));
                        String gln = request.getParameter("gln");
                        
                        if( gln.equals(shopKeeper.getGln()) || !DataAccess.existGLN(gln) ){
                        
                            if( !updateShopKeeper(request) ){
                                    message = MessageBuilder.buildMessage(7);
                                    url = "/administrador/actualizarempresas?key=" + request.getParameter("key") + "&operationType=updateShopKeeper";
                            }else{
                                /*Log log = new Log();
                                String userId = ((User) session.getAttribute("user")).getLogin();
                                String numberId = ((User) session.getAttribute("user")).getIdentificationNumber();
                                String description = "Establecimiento->"
                                                + request.getParameter("key")
                                                + ",Estado->"
                                                + request.getParameter("status"
                                                + request.getParameter("key"));
                                Transaction t = new Transaction();
                                log.saveData(userId, numberId, 23, description, "", t);
                                t.execute();*/
                                url = "/administrador/listaempresas?companyType=1";
                            }
                        }else{
                            message = "Error el GLN ya existe";
                            url = "/administrador/actualizarempresas?key=" + request.getParameter("key") + "&operationType=updateShopKeeper";
                        }
                    }
                }
	    }catch( Exception e ){
                System.out.println("Error-> "+e);
	        url="/logout";
	        message = MessageBuilder.buildMessage(15);
	    }

            request.setAttribute("message", message);
            RequestDispatcher dispatcher = getServletContext()
                            .getRequestDispatcher(url);
            dispatcher.forward(request, response);

	}

	/**
	 * Maneja el mètodo HTTP <code>GET</code>
	 * 
	 * @param request
	 *            peticiòn al servlet
	 * @param response
	 *            respuesta del servlet
	 */
	protected void doGet( HttpServletRequest request,
			HttpServletResponse response ) throws ServletException, IOException
	{
		processRequest(request, response);
	}

	/**
	 * Maneja el mètodo HTTP <code>POST</code>
	 * 
	 * @param request
	 *            peticiòn al servlet
	 * @param response
	 *            respuesta del servlet
	 */
	protected void doPost( HttpServletRequest request,
			HttpServletResponse response ) throws ServletException, IOException
	{
		processRequest(request, response);
	}

	/**
	 * Retorna una corta descripciòn del servlet.
	 */
	public String getServletInfo( )
	{
		return "Short description";
	}

	/**
	 * -Crea un objeto de tipo <CODE>Company</CODE> con el id de la empresa
	 * que se toma del request (companyId) 
         * -Asigna el nuevo estado al objeto (status) 
         * -Si se esta activando un mninorista se puede colocar como minorista exlcusivo de un proveedor en caso de que se halla 
         * seleccionado un proveedor
         * -Llama la función update() del objeto
	 * 
	 * @return booleano que indica si la actualización fué exitosa
	 * @param request Objeto request del servidor
	 */
	public boolean updateCompany( HttpServletRequest request )
	{

		int key = Integer.parseInt(request.getParameter("key"));
		Company company = new Company(key);
		company.setStatus(Integer.parseInt(request.getParameter("status" + key)));

                Transaction transaction = new Transaction();
		company.update(transaction);
		boolean success = transaction.execute();

		return success;
	}

	/**
	 * -Crea un objeto de tipo <CODE>Company</CODE> con el id de la empresa
	 * que se toma del request (companyId) -Asigna al objeto el estado
	 * "eliminada" -Llama la función update() del objeto
	 * 
	 * @return booleano que indica si la actualización fué exitosa
	 * @param request
	 *            Objeto request del servidor
	 */
	public boolean deleteCompany( HttpServletRequest request )
	{

		int companyId = Integer.parseInt(request.getParameter("item"));
		boolean success = false;

		if( !DataAccess.hasOrders(companyId) )
		{
			Company company = new Company(companyId);

			Transaction transaction = new Transaction();
			company.delete(transaction);
			success = transaction.execute();
		}
		return success;
	}
        
        
	/**
	 * -Crea un objeto de tipo <CODE>Store</CODE> con el id del establecimiento
	 * que se toma del request (key) 
         * -Carga los datos del formulario en el objeto
	 * -Llama la función update() del objeto
	 * 
	 * @return booleano que indica si la actualización fué exitosa
	 * @param request
	 *            Objeto request del servidor
	 */
	public boolean updateStore( HttpServletRequest request )
	{
                boolean success = false;

		String key = request.getParameter("key");
		Store store = new Store(Integer.parseInt(key));

                store.setName(request.getParameter("name"));
                store.setAddress(request.getParameter("address"));
                try{
                    store.setStreet(Integer.parseInt(request.getParameter("street")));
                }catch(NumberFormatException nfe){
                }
                try{
                    store.setAvenue(Integer.parseInt(request.getParameter("avenue")));
                }catch(NumberFormatException nfe){
                }
                store.setStreetOrientation(request.getParameter("streetOrientation"));
                store.setAvenueOrientation(request.getParameter("avenueOrientation"));
                store.setContact1(request.getParameter("contact1"));
                store.setPhoneNumber1(request.getParameter("phoneNumber1"));
                store.setGln(request.getParameter("gln"));
                try{
                    store.setNeighbourhood(Integer.parseInt(request.getParameter("neighbourhood")));
                }catch(NumberFormatException nfe){
                }
                
                Transaction transaction = new Transaction();
                store.update(transaction);
                success = transaction.execute();
                    
		return success;
	}

        
	/**
	 * -Crea un objeto de tipo <CODE>Supplier</CODE> con el id del proveedor
	 * que se toma del request (key) 
         * -Carga los datos del formulario en el objeto
	 * -Llama la función update() del objeto
	 * 
	 * @return booleano que indica si la actualización fué exitosa
	 * @param request
	 *            Objeto request del servidor
	 */
	public boolean updateSupplier( HttpServletRequest request )
	{
                boolean success = false;

		String key = request.getParameter("key");
		Company company = new Company(Integer.parseInt(key));

                company.setGln(request.getParameter("gln"));
                
                Transaction transaction = new Transaction();
                company.update(transaction);
                success = transaction.execute();
                    
		return success;
	}

        
	/**
	 * -Crea un objeto de tipo <CODE>ShopKeeper</CODE> con el id del minorista
	 * que se toma del request (key) 
         * -Carga los datos del formulario en el objeto
	 * -Llama la función update() del objeto
	 * 
	 * @return booleano que indica si la actualización fué exitosa
	 * @param request
	 *            Objeto request del servidor
	 */
	public boolean updateShopKeeper( HttpServletRequest request )
	{
                boolean success = false;

		String key = request.getParameter("key");
		Company company = new Company(Integer.parseInt(key));

                company.setGln(request.getParameter("gln"));
                
                Transaction transaction = new Transaction();
                company.update(transaction);
                success = transaction.execute();
                    
		return success;
	}
        
        
}