package com.ibatis.jpetstore.presentation.action;

import com.ibatis.jpetstore.domain.*;
import com.ibatis.jpetstore.presentation.form.*;
import org.apache.struts.action.*;

import javax.servlet.http.*;

public class SignonAction extends BaseAction {

  /* Public Methods */

  public ActionForward doPerform(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {

    request.getSession().removeAttribute("workingAccountForm");
    request.getSession().removeAttribute("accountForm");

    if (request.getParameter("signoff") != null) {
      request.getSession().invalidate();
      return mapping.findForward("success");
    } else {
      AccountForm acctForm = (AccountForm) form;

      String username = acctForm.getUsername();
      String password = acctForm.getPassword();
      String forwardAction = acctForm.getForwardAction();

      acctForm = new AccountForm();
      acctForm.setForwardAction(forwardAction);
      request.getSession().setAttribute("accountForm", acctForm);

      Account account = petStore.getAccount(username, password);



      if (account == null || account == null) {
        request.setAttribute("message", "Invalid username or password.  Signon failed.");
        return mapping.findForward("failure");
      } else {
        acctForm.setAccount(account);
        acctForm.getAccount().setPassword(null);

        acctForm.setMyList(petStore.getProductListByCategory(account.getFavouriteCategoryId()));

        if (acctForm.getForwardAction() == null || acctForm.getForwardAction().length() < 1) {
          return mapping.findForward("success");
        } else {
          //return mapping.findForward(acctForm.getForwardAction());
          response.sendRedirect(acctForm.getForwardAction());
          return null;
        }
      }
    }

  }


}
