package fanch.multijeu.numbers.data;

import android.content.Intent;

import java.text.ParseException;

public class ExpressionLexer {

    public static final char EOF = 0xff;
    protected static final String ALLOWED = "0123456789+-/%*()";
    public enum Lexem {
        P_OPEN,
        P_CLOSE,
        PLUS,
        MINUS,
        MULT,
        NUMBER,
        ERROR,
        EOF
    }

    protected String mData="";
    protected int    mIndex;
    protected Lexem  mLexem;
    protected String mString;
    protected char   mCurrent;


    public ExpressionLexer(String str)
    {
        mData=str;
        mIndex=-1;
    }

    public Lexem next()
    {
        mString="";
        while(!isValid() && !eof()) nextChar();

        if(eof()) return Lexem.EOF;
        if( (mCurrent>='0' && mCurrent<='9'))
        {
            /*if(mCurrent=='-')
            {
                mString+=mCurrent;
                nextChar();
            }*/
            while((mCurrent>='0' && mCurrent<='9') && !eof())
            {
                mString+=mCurrent;
                nextChar();
            }
            return mLexem=Lexem.NUMBER;
        }

        switch(mCurrent)
        {
            case '(': return doOp(Lexem.P_OPEN,'(');
            case ')': return doOp(Lexem.P_CLOSE,')');
            case '+': return doOp(Lexem.PLUS,'+');
            case '-': return doOp(Lexem.MINUS,'-');
            case '*': return doOp(Lexem.MULT,'*');
        }

        return doOp(Lexem.ERROR, "");
    }


    private Lexem doOp(Lexem l, char op)
    {
        return doOp(l, ""+op);
    }

    private Lexem doOp(Lexem l, String op)
    {
        mLexem=l;
        mString=op;
        nextChar();
        return mLexem;
    }

    public Lexem peek()
    {
        return mLexem;
    }

    public int getInt()
    {
        return Integer.parseInt(mString);
    }

    public String getString()
    {
        return mString;
    }

    private char nextChar()
    {
        mIndex++;
        if(mIndex>=mData.length()) return EOF;
        return mCurrent=mData.charAt(mIndex);
    }

    private boolean eof()
    {
        return mIndex>=mData.length();
    }

    private boolean isValid()
    {
        return isValid(mCurrent);
    }

    private boolean isValid(char c)
    {
        if(mIndex<0) return false;
        return ALLOWED.indexOf(c)>0;
    }



}
