package org.incava.doctorj;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.incava.java.*;
import org.incava.log.Log;


public class ItemCommentSpellCheck extends CommentSpellCheck
{
    public final static int NUM_CLOSEST_MATCHES = 6;

    private ItemDocAnalyzer analyzer;

    private JavadocElement desc;

    private LineMapping lines = null;

    public void check(ItemDocAnalyzer analyzer, JavadocElement desc)
    {
        this.analyzer = analyzer;
        this.desc = desc;
        this.lines = null;
        
        super.check(desc.text);
    }
    
    protected String makeMessage(String word, List nearMatches)
    {
        StringBuffer buf = new StringBuffer("Word '" + word + "' appears to be misspelled. ");
        if (nearMatches.size() == 0) {
            buf.append("No close matches");
        }
        else {
            buf.append("Closest matches: ");
            int nWords = 0;
            Iterator it = nearMatches.iterator();
            while (it.hasNext() && nWords < NUM_CLOSEST_MATCHES) {
                List matches = (List)it.next();
                if (matches != null) {
                    Iterator mit = matches.iterator();
                    while (mit.hasNext() && nWords < NUM_CLOSEST_MATCHES) {
                        String w = (String)mit.next();
                        Log.log("adding word: " + w);
                        if (nWords > 0) {
                            buf.append(", ");
                        }
                        buf.append(w);
                        ++nWords;
                    }
                }
            }
        }
        return buf.toString();
    }

    protected void wordMisspelled(String word, int position, List nearMatches)
    {
        Log.log("word: '" + word + "', position: " + position + ", nearMatches: " + nearMatches);

        if (lines == null) {
            lines = new LineMapping(desc.text, desc.start.line, desc.start.column);
        }
        
        Location start = lines.getLocation(position);
        Log.log("start: " + start);
        
        Location end = lines.getLocation(position + word.length() - 1);
        Log.log("end: " + end);
        
        String msg = makeMessage(word, nearMatches);
        Log.log("msg: " + msg);
        
        analyzer.addViolation(msg, start, end);
    }
}
