package us.semanter.app.ui;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.inputmethod.CompletionInfo;
import android.widget.EditText;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import us.semanter.app.model.Tag;

public class TagEditor extends EditText {
    List<TagListener> listeners;

    public TagEditor(Context context, AttributeSet attrs) {
        super(context, attrs);

        listeners = new Vector<TagListener>();
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_ENTER) {
            dispatchAll(allToTags());
        } else if(keyCode == KeyEvent.KEYCODE_SPACE) {
            Log.d("TagEditor", getSelectionStart() + ", " + getText().length());
            if(getSelectionStart() == getText().length() - 1) { // at end of field?
                dispatchAll(allToTags());
            }
        }

        return false;
    }

    private List<Tag> allToTags() {
        String text = getText().toString();

        int numSpaces = countMatches(text, " ");
        ArrayList<Tag> tags = new ArrayList<Tag>(numSpaces+1);

        String[] parts = text.split(" ");
        for(String rawName: parts)
            tags.add(new Tag(rawName.trim()));

        return tags;
    }

    private int countMatches(String text, String match) {
        return text.length() - text.replace(match, "").length();
    }

    /**
     * Event Source
     */

    private void dispatch(Tag tag) {
        Log.d("TagEditor", tag.getValue());
        for(TagListener listener: listeners) {
            listener.onNewTag(tag);
        }
    }

    private void dispatchAll(List<Tag> tags) {
        for(Tag tag: tags) dispatch(tag);
    }

    public void registerListener(TagListener listener) {
        listeners.add(listener);
    }

    public interface TagListener {
        public void onNewTag(Tag newTag);
    }
}

@@ -162,103 +162,23 @@
 oid.
-view.inputmethod.CompletionInfo;%0Aimport android.widget.EditText;%0Aimport android.widget.TextView
+widget.EditText
 ;%0A%0Ai
@@ -660,32 +660,57 @@
 l(allToTags());%0A
+            setText(%22%22);%0A
         %7D else i
@@ -947,32 +947,61 @@
 l(allToTags());%0A
+                setText(%22%22);%0A
             %7D%0A  

Clear EditText after tags added.