import jedi as jedi
from jedi.api import *

def findDefinition(source, line, column, path):
#    print "source: " + source
#    print "line: " + str(line)
#    print "column: " + str(column)
#    print "path: " + path
    script = jedi.Script(source=source, line=line, column=column, path=path)
    defs = script.goto_definitions()
#    print "found defs: " + repr(defs)
#    print "len defs: " + str(len(defs))

    result = ""
    
    if len(defs):
        aDef = defs[0]
        filePath = aDef.module_path
        lineNum = aDef.line
    
        result = filePath + ":" + str(lineNum)
    
#    print "returning :" + repr(result)
    return result

def findCompletions(source, line, column, path, lineStartIdx, insIdx, selIdx):
#    import sys; print "completions : " + str(sys.executable)

    script = jedi.Script(source=source, line=line, column=column, path=path)
    comps = script.completions()
    
    prefix = source[insIdx:selIdx]
    # print('prefix: `' + prefix + '`')
    
    n = source[selIdx:selIdx+1]
    
    result = []
    for comp in comps:
        nameStr = comp.name
        # print(nameStr)
        
        if n != '(' and ('function' == comp.type or 'class' == comp.type):
            try:
                callStr = nameStr + ''
                callStr += '('
                tmpSrc = source[:insIdx] + callStr
                # print tmpSrc
                col = insIdx + len(callStr) - lineStartIdx
                # print col
                tmpScript = jedi.Script(source=tmpSrc, column=col)
                sigs = tmpScript.call_signatures()
                # print "sigs: " + repr(sigs)
                if (len(sigs)):
                    assert len(sigs) == 1
                    params = sigs[0].params
                    paramsLen = len(params)
                    if paramsLen:
                        i = 0
                        for param in params:
                            tok = param.token_list[0]
                            # print tok
                            # print tok.__class__ # jedi.parser.representation.Name
                            code = repr(tok.get_code())
                            callStr += '${' + code[1:-1] + '}'
                            if i < paramsLen - 1:
                                callStr += ', '
                            i += 1
                        callStr += ')'
                    else:
                        callStr += '${})'
                else:
                    callStr += '${})'
                result.append(callStr)
                result.append(nameStr)
            except:
                pass
        elif prefix != nameStr:
            result.append(nameStr)

    # print "returning: " + repr(result)
    return result

