# Copyright (C) 2017 The Meme Factory, Inc.  http://www.meme.com/
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# Karl O. Pinc <kop@meme.com>

'''
Lexical anlyzer for file name convention rules
'''

import ply.lex as lex
from . import exceptions as ex


reserved_str = {
    '.': 'PERIOD',
}

reserved_user_str = {
    '<entity>'       : 'ENTITY',
    '<last 4 digits>': 'LAST_4_DIGITS',
    '<yyyy>'         : 'YEAR',
}

tokens = [
    'DASH',
    'LBRACE',
    'RBRACE',
    'SPACE',
    'DATE',
    'HASH',
    'PAREN_STR',
    'WORD',
    'USER_STR',
    'VERSION',
] + list(reserved_str.values()) + list(reserved_user_str.values())

# Simple tokens
t_DASH          = r'\ -\ '
t_LBRACE        = r'\['
t_RBRACE        = r'\]'
t_SPACE         = r'\ '
t_DATE          = r'<yyyy-mm-dd>'    # no '-' allowed in USER_STR
t_HASH          = r'<\#>'            # no '#' allowed in USER_STR
t_PAREN_STR     = r'\ \([A-Za-z0-9,\ \#\.]+\)'


# Rules that do things.

def t_VERSION(tok):
    r'\ v<\#>'
    return tok


def t_USER_STR(tok):
    r'<[a-z0-9\(\)\ /]+>'
    # Check for reserved user strings
    tok.type = reserved_user_str.get(tok.value, 'USER_STR')
    return tok


def t_WORD(tok):
    r"[A-Za-z0-9,\#\.\-'&]+"
    # Check for reserved words
    tok.type = reserved_str.get(tok.value, 'WORD')
    return tok


# Error handling rule
def t_error(tok):
    raise ex.LexError(lexer.lexpos, lexer.lexdata, tok.value)


lexer = lex.lex()
