package jp.sourceforge.nicoro.nicoscript;

import static jp.sourceforge.nicoro.Log.LOG_TAG;
import jp.sourceforge.nicoro.Log;
import jp.sourceforge.nicoro.MessageChatController;
import jp.sourceforge.nicoro.MessageChatFork;
import jp.sourceforge.nicoro.Release;

//TODO とりあえずparseだけでメイン動作は後で実装
//TODO @button考慮

public class NicoScriptDoor extends NicoScript
implements NicoScript.NicosOrLocal {
    private static final boolean DEBUG_LOGD = Release.IS_DEBUG & true;

    protected static final String COMMAND = "ドア";

    private final MultiKeyword mMultiKeyword = new MultiKeyword();

    private int mCount;

    protected NicoScriptDoor(MessageChatFork chat, CommandSplitter commandSplitter) {
        super(chat);
        if (chat.getTime() < 0) {
            chat.setTime(UNDEFINED_DEFAULT_TIME);
        }

        mCount = 5;

        String keyword = commandSplitter.getNextCommand();
        if (keyword == null) {
            mMultiKeyword.setKeyword("左、右");
            return;
        }
        mMultiKeyword.setKeyword(keyword);

        // TODO 方向とカウントの反映
        String direction = commandSplitter.getNextCommand();
        if (direction == null) {
            direction = "左右";
            return;
        }

        String count = commandSplitter.getNextCommand();
        if (count == null) {
            return;
        }
        try {
            mCount = getInt(count);
        } catch (NumberFormatException e) {
            Log.e(LOG_TAG, e.toString(), e);
        }

        String agreeEntirely = commandSplitter.getNextCommand();
        if (agreeEntirely == null) {
            return;
        }
        if (!mMultiKeyword.setAgreeEntirely(agreeEntirely)) {
            Log.w(LOG_TAG, Log.buf().append("invalid Door: agreeEntirely=")
                    .append(agreeEntirely).toString());
            return;
        }
    }

    @Override
    public void onPrepareRemove(MessageChatController controller) {
        controller.clearCommandDoor(this);
        if (DEBUG_LOGD) {
            Log.d(LOG_TAG, Log.buf().append("End NicoScript Door: ")
                    .append(mChat).toString());
        }
    }
    @Override
    public void onDraw(MessageChatController controller) {
        controller.setCommandDoor(this);
        if (DEBUG_LOGD) {
            Log.d(LOG_TAG, Log.buf().append("Start NicoScript Door: ")
                    .append(mChat).toString());
        }
    }

    @Override
    public boolean isSaveLocal() {
        return mChat.isSaveLocal();
    }

    // XXX どれがマッチしたか分からないとまずい
    @Override
    public boolean match(String text) {
        return mMultiKeyword.match(text);
    }

    public int getCount() {
        return mCount;
    }
}
