/*
 * $Id: ChatLog.java 223 2007-10-14 08:07:40Z sugimotokenichi $
 * Copyright (C) 2005 SUGIMOTO Ken-ichi
 * 作成日： 2005/03/11
 */
package feat2.testapp.flash;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * チャットログを保存するクラス。
 * @author SUGIMOTO
 */
public class ChatLog {

    private static ChatMessage[] messageLog = new ChatMessage[100];
    private static int nextIndex = 0;
    private static Log log = LogFactory.getLog(ChatLog.class);

    synchronized public static void addMessage(ChatMessage m) {
        if ( m == null || m.getMessage() == null ) {
            return;
        }
        m.setIndex(nextIndex);
        messageLog[(nextIndex++)%100] = m;
        log.info(m.toString());
        log.info("メッセージ追加");
        String logfile = System.getProperty("chat.logfile");
        if ( logfile != null ) {
            try {
                File f = new File(logfile);
                FileWriter w = new FileWriter(f, true);
                w.write(m.toString());
                w.write("\n");
                w.flush();
                w.close();
            }
            catch (IOException ex) {
            }
        }
    }

    synchronized public static ChatMessage getMessage(int index) {
        if ( 0 <= index && nextIndex-100 <= index && index < nextIndex )
            return messageLog[index%100];

        if ( -100 <= index && index < 0 && 0 <= nextIndex+index )
            return messageLog[(nextIndex+index)%100];

        return null;
    }

    synchronized public static int getNextIndex() {
        return nextIndex;
    }
}
