/*
 * Aipo is a groupware program developed by Aimluck,Inc.
 * Copyright (C) 2004-2008 Aimluck,Inc.
 * http://aipostyle.com/
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package com.aimluck.eip.modules.actions.account;

import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import org.apache.cayenne.access.DataContext;
import org.apache.cayenne.exp.Expression;
import org.apache.cayenne.exp.ExpressionFactory;
import org.apache.cayenne.query.SelectQuery;
import org.apache.jetspeed.portal.portlets.VelocityPortlet;
import org.apache.jetspeed.services.logging.JetspeedLogFactoryService;
import org.apache.jetspeed.services.logging.JetspeedLogger;
import org.apache.turbine.util.RunData;
import org.apache.velocity.context.Context;

import com.aimluck.commons.field.ALStringField;
import com.aimluck.eip.cayenne.om.security.TurbineUser;
import com.aimluck.eip.modules.actions.common.ALBaseAction;
import com.aimluck.eip.orm.DatabaseOrmService;
import com.aimluck.eip.util.ALCellularUtils;

/**
 * ログイン画面を表示するアクションクラスです。
 * 
 */
public class CellAccountLoginAction extends ALBaseAction {

  private static final JetspeedLogger logger = JetspeedLogFactoryService
      .getLogger(CellAccountLoginAction.class.getName());

  private String org_id;

  /**
   * @param portlet
   * @param context
   * @param rundata
   * @throws java.lang.Exception
   * @see org.apache.jetspeed.modules.actions.portlets.VelocityPortletAction#buildNormalContext(org.apache.jetspeed.portal.portlets.VelocityPortlet,
   *      org.apache.velocity.context.Context, org.apache.turbine.util.RunData)
   */
  protected void buildNormalContext(VelocityPortlet portlet, Context context,
      RunData rundata) throws Exception {

    String action_logout = rundata.getParameters().getString("logout", "")
        .trim();
    if ("T".equals(action_logout)) {
      setTemplate(rundata, "accountlogout-info");
    }

    org_id = DatabaseOrmService.getInstance().getOrgId(rundata);

    doAccount_login(rundata, context);
    setResultData(this);
    putData(rundata, context);
  }

  public void doAccount_login(RunData rundata, Context context)
      throws Exception {
    boolean enableEasyLogin = false;
    String username = null;
    String key = rundata.getParameters().getString("key", "").trim();
    StringTokenizer st = new StringTokenizer(key, "_");

    if (st.countTokens() == 2) {
      username = st.nextToken();
      String base64value = st.nextToken();

      // 入力されたユーザ名を検証する．
      ALStringField tmpname = new ALStringField();
      tmpname.setTrim(true);
      tmpname.setNotNull(true);
      tmpname.setCharacterType(ALStringField.TYPE_ALPHABET_NUMBER);
      tmpname.limitMaxLength(16);
      tmpname.setValue(username);
      boolean valid = tmpname.validate(new ArrayList());

      if (valid) {
        // ALEipUser eipuser = ALEipUtils.getALEipUser(username);

        DataContext dataContext = DataContext.createDataContext(org_id);
        Expression exp = ExpressionFactory.matchExp(
            TurbineUser.LOGIN_NAME_PROPERTY, username);
        SelectQuery query = new SelectQuery(TurbineUser.class, exp);
        List users = dataContext.performQuery(query);
        if (users.size() != 0) {
          TurbineUser tuser = (TurbineUser) users.get(0);

          if (!(ALCellularUtils.getCheckValueForCellLogin(username, tuser
              .getUserId().toString())).equals(base64value)) {
            username = "";
          }

          String uid = tuser.getCellularUid();
          enableEasyLogin = (uid != null && uid.length() > 0);
        } else {
          username = "";
        }
      } else {
        username = "";
      }
    }

    context.put("username", username);
    context.put("key", key);
    context.put("enableEasyLogin", Boolean.valueOf(enableEasyLogin));
  }

  /**
   * 簡易ログイン説明ページを表示する． <BR>
   * 
   * @param rundata
   * @param context
   * @throws Exception
   */
  public void doAccount_info(RunData rundata, Context context) throws Exception {
    doAccount_login(rundata, context);
    setTemplate(rundata, "accountlogin-info");
  }

  public String getCompanyId() {
    return DatabaseOrmService.getInstance().getCompanyId(org_id);
  }
}
