/*
 * Copyright 2007 Kickmogu Co. Ltd. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 
 * either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */



/*
 * 作成日: 2006/12/13
 *
 * TODO この生成されたファイルのテンプレートを変更するには次へジャンプ:
 * ウィンドウ - 設定 - Java - コード・スタイル - コード・テンプレート
 */
package com.kickmogu.rhythm.core;

import com.kickmogu.Config;
import com.kickmogu.Util;
import java.util.*;
import org.apache.log4j.Category;

public class SessionManager {
	static Category log = Category.getInstance(SessionManager.class.getName());

	private static Map<String, LoginSession> sessions = new HashMap<String, LoginSession>();
	
	static private int getTimeoutMin() {
		return Integer.parseInt(Config.getProperty("session.timeout"));
	}
	
	static public boolean isValidSession(String sessionid, int memberid) {
		if (sessionid == null) {
			log.info("sessionid is null");
			return false;
		}
		LoginSession target = sessions.get(sessionid);
		if (target == null) {
			log.info("sessionid not found:" + sessionid + "," + memberid);
			return false;
		}
		Date now = new Date();
		if (now.getTime() - getTimeoutMin() * 60 * 1000 > target.getRegistDate().getTime()) {
			log.info("session timeout:" + sessionid + "," + memberid + "," + target.getRegistDate());
			return false;
		}
		if (memberid != target.getMemberId()) {
			log.info("member unmatch:" + sessionid + "," + memberid + "," + target.getMemberId());
			return false;
		}
		target.setRegistDate(now);
		return true;
	}
	
	static public String addSession(int memberid) {
		LoginSession newsession = new LoginSession();
		newsession.setMemberId(memberid);
		newsession.setRegistDate(new Date());
		String sessionid = Util.createPassword(40);
		sessions.put(sessionid, newsession);
		return sessionid;
	}
}
