# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#

from .ply import lex

TOKEN_INT = 'INTEGER'
TOKEN_FLOAT = 'FLOAT'
TOKEN_VECTOR3 = 'VECTOR3'
TOKEN_VECTOR4 = 'VECTOR4'
TOKEN_STRING = 'STRING'
TOKEN_NEWLINE = 'NEWLINE'
TOKEN_OPEN_BRACE = 'OPEN_BRACE'
TOKEN_CLOSE_BRACE = 'CLOSE_BRACE'
TOKEN_EQUALS = 'EQUALS'
TOKEN_COMMENT_SINGLELINE = 'COMMENT_SINGLELINE'
TOKEN_COMMENT_MULTILINE = 'COMMENT_MULTILINE'
TOKEN_NAME = 'NAME'

tokens = [
    TOKEN_INT,
    TOKEN_FLOAT,
    TOKEN_VECTOR3,
    TOKEN_VECTOR4,
    TOKEN_STRING,
    TOKEN_NEWLINE,
    TOKEN_OPEN_BRACE,
    TOKEN_CLOSE_BRACE,
    TOKEN_EQUALS,
    TOKEN_COMMENT_SINGLELINE,
    TOKEN_COMMENT_MULTILINE,
    TOKEN_NAME,
]

# A string containing ignored characters (spaces and tabs)
t_ignore = ' \t'

def t_FLOAT(t):
    r'[-+]?[0-9]*\.[0-9]+([eE][-+]?[0-9]+)?\s'
    t.value = float(t.value)
    return t
    
def t_INTEGER(t):
    r'[-+]?[0-9][0-9XxA-Fa-f]*\s'
    t.value = int(t.value)
    return t
    
def t_OPEN_BRACE(t):
    r'\{\s'
    return t

def t_CLOSE_BRACE(t):
    r'\}\s'
    return t

def t_EQUALS(t):
    r'\=\s'
    return t
    
def t_COMMENT_SINGLELINE(t):
    r'\/\/.*\n'
    t.lexer.lineno += len([a for a in t.value if a=="\n"])

#Found at http://ostermiller.org/findcomment.html
def t_COMMENT_MULTILINE(t):
    r'/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+/'
    if t.value.startswith("/**") or t.value.startswith("/*!"):
        #not sure why, but get double new lines
        v = t.value.replace("\n\n", "\n")
        #strip prefixing whitespace
        v = re.sub("\n[\s]+\*", "\n*", v)
    t.lexer.lineno += len([a for a in t.value if a=="\n"])

def t_NEWLINE(t):
    r'\n'
    t.lexer.lineno += 1
    
def t_VECTOR3(t):
    r'\"\s?([-+]?[0-9]*\.[0-9]+([eE][-+]?[0-9]+)?\s){2}[-+]?[0-9]*\.[0-9]+([eE][-+]?[0-9]+)?\s?\"'
    t.value = t.value[1:-1]
    return t

def t_VECTOR4(t):
    r'\"\s?([-+]?[0-9]*\.[0-9]+([eE][-+]?[0-9]+)?\s){3}[-+]?[0-9]*\.[0-9]+([eE][-+]?[0-9]+)?\s?\"'
    t.value = t.value[1:-1]
    return t
    
def t_STRING(t):
    r'\".*?\"'
    t.value = t.value[1:-1]
    return t

def t_NAME(t):
    r'\S+'
    return t

def t_error(t):
    print("Lexer: Illegal character %s" % t.value[0])
    t.lexer.skip(1)

lexer = lex.lex()
