package jp.sourceforge.nicoro.nicoscript;

import java.lang.ref.WeakReference;
import java.util.regex.Pattern;

import jp.sourceforge.nicoro.MessageChatController;
import jp.sourceforge.nicoro.MessageChatFork;

public abstract class NicoScript {
    private static final char COMMAND_START_0 = '＠';
    private static final char COMMAND_START_1 = '@';
    private static final String COMMAND_SPLIT = " 　";
    private static WeakReference<Pattern> sRefCommandSplit =
        new WeakReference<Pattern>(Pattern.compile(COMMAND_SPLIT));
    
    protected MessageChatFork mChat;
    
    protected NicoScript(MessageChatFork chat) {
        mChat = chat;
    }
    
    public void onPrepareRemove(MessageChatController controller) {
        // デフォルトは何もしない
    }
    public void onDraw(MessageChatController controller) {
        // デフォルトは何もしない
    }

    public static NicoScript createNicoScript(String text, MessageChatFork chat) {
        assert text != null;
        int textLength = text.length();
        if (textLength == 0) {
            return null;
        }
        char text0 = text.charAt(0);
        if (text0 != COMMAND_START_0 && text0 != COMMAND_START_1) {
            return null;
        }
        
        Pattern commandSplit = getCommandSplit();
        String[] commands = commandSplit.split(text.substring(1));
        if (commands == null || commands.length == 0) {
            return null;
        }
        String commandMain = commands[0];
        assert commandMain != null;
        if (NicoScriptDefault.COMMAND.equals(commandMain)) {
            return new NicoScriptDefault(chat);
        } else if (NicoScriptGyaku.COMMAND.equals(commandMain)) {
            return new NicoScriptGyaku(chat, commands);
        }
        
        return null;
    }
    
    private static Pattern getCommandSplit() {
        Pattern p = sRefCommandSplit.get();
        if (p == null) {
            p = Pattern.compile(COMMAND_SPLIT);
            sRefCommandSplit = new WeakReference<Pattern>(p);
        }
        return p;
    }
}
