# -*- coding: utf-8 -*-

# For debugging
# NVIM_PYTHON_LOG_FILE=nvim.log NVIM_PYTHON_LOG_LEVEL=INFO nvim

import os
import re
import logging
import jedi
from neovim import attach, setup_logging

logger = logging.getLogger(__name__)

class Handler:

    def __init__(self,nvim):

        self._nvim = nvim

    def cm_on_changed(self,info,ctx):

        lnum = ctx['curpos'][1]
        col = ctx['curpos'][2]
        line = self._nvim.current.buffer[lnum-1]
        typed = line[0 : col-1]

        # self.refresh_keyword_incr(line)

        kwtyped = re.search(r'[0-9a-zA-Z_]*?$',typed).group(0)
        startcol = col-len(kwtyped)
        if kwtyped=="" and len(typed) and typed[-1]=='.':
            pass
        else:
            return

        matches = []

        path = self._nvim.eval('expand("%:p")')
        src = "\n".join(self._nvim.current.buffer[:])
        scr = jedi.Script(src, lnum, col-1, path)
        completions = scr.completions()

        for complete in completions:
            item = dict(word=kwtyped+complete.complete,icase=1,dup=1,abbr=complete.name)
            matches.append(item)

        # cm#complete(src, context, startcol, matches)
        ret = self._nvim.call('cm#complete', info['name'], ctx, startcol, matches)

        logger.info('on changed, current line: %s, typed: %s, matches: %s, ret: %s', line, typed, matches, ret)

def main():

    # logging setup
    level = logging.INFO
    if 'NVIM_PYTHON_LOG_LEVEL' in os.environ:
        # TODO this affects the log file name
        setup_logging('cm_jedi')
        l = getattr(logging,
                os.environ['NVIM_PYTHON_LOG_LEVEL'].strip(),
                level)
        if isinstance(l, int):
            level = l
    logger.setLevel(level)

    # connect neovim
    nvim = attach('stdio')
    nvim_event_loop(nvim)

def nvim_event_loop(nvim):

    handler = Handler(nvim)

    def on_setup():
        logger.info('on_setup')

    def on_request(method, args):
        raise Exception('Not implemented')

    def on_notification(method, args):
        nonlocal handler
        logger.info('method: %s, args: %s', method, args)

        func = getattr(handler,method,None)
        if func is None:
            return

        func(*args)

    nvim.run_loop(on_request, on_notification, on_setup)

main()


@@ -625,16 +625,17 @@
 wtyped)%0A
+%0A
         
@@ -641,53 +641,261 @@
  if 
-kw
+len(
 typed
+)
 ==
-%22%22 and
+0:%0A            return%0A        elif
  len(
+kw
 typed)
- and typed%5B-1%5D=='.'
+%3E=2:%0A            pass%0A        elif len(kwtyped):%0A            return%0A        elif typed%5B-1%5D=='.':%0A            pass%0A        elif (typed%5B-1%5D==' ') and (typed%5B0:5%5D=='from ' or typed%5B0:7%5D=='import ')
 :%0A  
@@ -1104,21 +1104,26 @@
 , lnum, 
-col-1
+len(typed)
 , path)%0A
@@ -1389,14 +1389,8 @@
     
- ret =
  sel
@@ -1453,16 +1453,28 @@
  matches
+, async=True
 )%0A%0A     
@@ -1530,32 +1530,12 @@
 ed: 
-%25s, matches: %25s, ret: 
+%5B
 %25s
+%5D
 ', l
@@ -1548,22 +1548,8 @@
 yped
-, matches, ret
 )%0A%0Ad

optimize jedi completion