# coding= utf-8

# todo 1 (interaction, feature) +1: multiline TODO
#  todo 2131 (interaction, feature) +0: popup todo history

# todo 232 (feature) +1: introduce sub-todo's that are part of other, todo yyy: becomes xxx/yyy
#  todo 2141 (feature) +0: 232, create sub-todo's with inherited state and priority


import sublime, sublime_plugin
import sys, re

if sys.version < '3':
    from db import *
    from cache import *
    from c import *
else:
    from .db import *
    from .cache import *
    from .c import *



#callback at end of fetching DB
def dbMaintainance():
    cWnd= sublime.active_window()
    if not cWnd: return

    cView= cWnd.active_view()
    if not cView: return

    cView.run_command('typetodo_maintain', {})



class TypetodoEvent(sublime_plugin.EventListener):
    mutexUnlocked= 1
    view= None



#   React on all Sublime window close event.
#   React on switching project in window.

    def on_deactivated(self, _view):
#  todo 1783 (cleanup, uncertain) -1: switching project in window not clearly fixed, need review
        sublime.set_timeout(lambda: self.on_activated(_view), 200) #spike to catch switching project in existing window

        sublime.set_timeout(WCache().exitHandler, 0) #sublime's timeout is needed to let sublime.windows() be [] at exit





#   React on switching into view, initializing DB fetch-synchronize-save.
#   Switching into view actually duplicated number of times with several
#    handlers, but this handler is main and is used for TodoDb() creation.

    def on_activated(self, _view):
        constCorrect(_view) #coz settings are delayed at load

        cDb= WCache().getDB(True, dbMaintainance) #really applies only once

        #set 'file' syntax where it is not right and check consistency
        if cDb: