/*
 * Created on 2004-08-21
 *
 * Part of the Symbian development plug-in for Eclipse
 * Copyright (C) Mikołaj Zalewski, 2004
 */
package pl.zalewski.mikolaj.symbdev.errorparsers;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.core.ErrorParserManager;
import org.eclipse.cdt.core.IErrorParser;

/**
 * @author mikolaj
 *
 * This error parser reads the strings that are shown by ABDL before runnning
 * a command, like "command.exe", "perl -S command.pl" and loads the
 * appropriate error parser
 */
public class AdaptiveErrorParser implements IErrorParser {

    final static String VISUAL_C_PARSER="org.eclipse.cdt.core.VCErrorParser";
    final static String VISUAL_LINK_PARSER="pl.zalewski.mikolaj.symbdev.MsLinkErrorParser";
    final static String SYMBIAN_RCCOMP_PARSER="pl.zalewski.mikolaj.symbdev.RCCompErrorParser";
    
    /**
     * Default constructor 
     */
    public AdaptiveErrorParser() {
        super();
        fCmdPattern=Pattern.compile("^\t?([\\w_]+)\\.exe.*");
        fPerlPattern=Pattern.compile("^\t?perl\\s+-S\\s+([\\w_\\.]+).*");
        fMMPFilePattern=Pattern.compile("MMPFILE\\s+\"(.*)\\.MMP\"");
        fCmdToParsers=new HashMap();
        fCmdToParsers.put("cl", getErrorParser(VISUAL_C_PARSER));
        fCmdToParsers.put("link", getErrorParser(VISUAL_LINK_PARSER));
        fCmdToParsers.put("epocrc.pl", getErrorParser(SYMBIAN_RCCOMP_PARSER));
    }
    
    protected IErrorParser getErrorParser(String p)
    {
        IErrorParser[] tabparse=CCorePlugin.getDefault().getErrorParser(p);
        if (tabparse.length!=0)
            return tabparse[0];
        System.out.println("Couldn't load parser "+p);
        return null;
    }
    
    boolean checkPattern(Pattern p, String line)
    {
        Matcher matcher=p.matcher(line);
        if (matcher.matches())
        {
            String command=matcher.group(1);
            fCurrParser=(IErrorParser)fCmdToParsers.get(command);
            return true;
        }
        return false;
    }

    /* (non-Javadoc)
     * @see org.eclipse.cdt.core.IErrorParser#processLine(java.lang.String, org.eclipse.cdt.core.ErrorParserManager)
     */
    public boolean processLine(String line, ErrorParserManager eoParser) {
        if (checkPattern(fCmdPattern, line)) return true;
        if (checkPattern(fPerlPattern, line)) return true;
        
        Matcher matcher=fMMPFilePattern.matcher(line);
        if (matcher.matches())
        {
            String fileName=matcher.group(1);
            fCurrParser=new MMPFileErrorParser();
            return true;
        }
        
        if (fCurrParser!=null)
            return fCurrParser.processLine(line, eoParser);
        return false;
    }
    
    Pattern fCmdPattern;
    Pattern fPerlPattern;
    Pattern fMMPFilePattern;
    Map fCmdToParsers;
    IErrorParser fCurrParser;
}
