import commands
import time
from tab import StackTabber
from method import Method 
from mode import Fundamental
from lex import Grammar, PatternRule, RegionRule, PatternMatchRule
from mode.python import StringGrammar1, StringGrammar2
from mode.pipe import Pipe
from method.shell import Interact

chr1 = '[a-zA-Z_]'
chr2 = '[a-zA-Z_0-9]'
word = chr1 + chr2 + '*'

class LuaGrammar(Grammar):
    rules = [
        PatternRule('comment', r'--.*$'),
        PatternRule('spaces', r' +'),
        PatternRule('eol', r'\n'),

        RegionRule('lua.string', r"'", StringGrammar1, r"'"),
        RegionRule('lua.string', r'"', StringGrammar2, r'"'),

        PatternMatchRule('x', '(function)( +)('+word+')',
                         'lua.keyword', 'spaces', 'lua.function'),
        PatternRule('lua.keyword', '(?:while|until|true|then|return|repeat|or|not|nil|local|in|if|function|for|false|end|elseif|else|done|do|break|and)(?!'+chr2+')'),
        PatternRule('lua.internal', '_[A-Z]+'),
        PatternRule('lua.identifier', word),

        PatternRule('delimiter', r'(?:[=(){}\[\];:,.])'),
        PatternRule('lua.operator', r'(?:\.\.\.|\.\.|==|~=|<=|>=|<|>)'),
        PatternRule('lua.operator', r'(?:\+|-|/|\*|%|\^)'),

        PatternRule('lua.integer', r"(?<![\.0-9a-zA-Z_])(?:0|-?[1-9][0-9]*|0[0-7]+|0[xX][0-9a-fA-F]+)[lL]?(?![\.0-9a-zA-Z_])"),
        PatternRule('lua.float', r"(?<![\.0-9a-zA-Z_])(?:-?[0-9]+\.[0-9]*|-?\.[0-9]+|(?:[0-9]|[0-9]+\.[0-9]*|-?\.[0-9]+)[eE][\+-]?[0-9]+)(?![\.0-9a-zA-Z_])"),
    ]

class LuaCheckSyntax(Method):
    '''Check the syntax of a lua file'''
    def _execute(self, w, **vargs):
        app = w.application
        cmd = "luac -p %r" % (w.buffer.path)
        (status, output) = commands.getstatusoutput(cmd)
        if status == 0:
            app.set_error("Syntax OK")
            app.data_buffer("*Lua-Check-Syntax*", output, switch_to=False)
        else:
            app.data_buffer("*Lua-Check-Syntax*", output)

class LuaStart(Interact):
    args = []
    modename = 'luapipe'
    reuse = True
    def _execute(self, w, **vargs):
        Interact._execute(self, w, bname='*Lua*', cmd='lua')
class LuaLoadFile(Interact):
    args = []
    modename = 'luapipe'
    reuse = True
    def _execute(self, w, **vargs):
        Interact._execute(self, w, bname='*Lua*', cmd='lua')
        b = w.application.get_buffer_by_name('*Lua*')
        path = w.buffer.path
        b.pipe_write('dofile("' + path + '");\n')

class Lua(Fundamental):
    name        = 'Lua'
    extensions  = ['.lua']
    grammar     = LuaGrammar
    commentc    = '--'
    opentokens  = ('delimiter',)
    opentags    = {'(': ')', '[': ']', '{': '}'}
    closetokens = ('delimiter',)
    closetags   = {')': '(', ']': '[', '}': '{'}
    colors      = {}
    actions     = [LuaCheckSyntax, LuaStart, LuaLoadFile]
    _bindings   = {
        'close-paren':      (')',),
        'close-brace':      ('}',),
        'close-bracket':    (']',),
        'lua-check-syntax': ('C-c s',),
    }

class LuaPipe(Pipe):
    name    = 'luapipe'
    grammar = LuaGrammar

def install(*args):
    Lua.install(*args)
    LuaPipe.install(*args)