import sublime
import sublime_plugin


def plugin_loaded():
    global close_sidebar_if_opened
    global settings
    global settings_base

    settings = sublime.load_settings("FocusFileOnSidebar.sublime-settings")
    settings_base = sublime.load_settings("Preferences.sublime-settings")
    plugin_reload()
    settings.add_on_change('reload', plugin_reload)
    settings_base.add_on_change('focusfileonsidebar-reload', plugin_reload)


def plugin_reload():
    global close_sidebar_if_opened
    close_sidebar_if_opened = settings_base.get(
        'close_sidebar_if_opened', settings.get('close_sidebar_if_opened'))


def plugin_unloaded():
    settings.clear_on_change('reload')
    settings_base.clear_on_change('focusfileonsidebar-reload')

def refresh_folders(self):
    data = get_project_json(self)
    set_project_json(self, {})
    set_project_json(self, data)


def get_project_json(self):
    return self.window.project_data()


def set_project_json(self, data):
    return self.window.set_project_data(data)


class FocusFileOnSidebar(sublime_plugin.WindowCommand):
    def run(self):
        if not self.window.is_sidebar_visible():
            self.window.set_sidebar_visible(True)
            self.window.run_command("reveal_in_side_bar")
            # Without the timeout the command on the palette doesn't work
            sublime.set_timeout(
                lambda: self.window.run_command('focus_side_bar'), 50)
        else:
            if close_sidebar_if_opened:
                self.window.set_sidebar_visible(False)
                sublime.set_timeout(lambda: refresh_folders(self), 50)
            else:
                self.window.run_command("reveal_in_side_bar")
                self.window.run_command('focus_side_bar')

@@ -1019,16 +1019,151 @@
 (data)%0A%0A
+def reveal_and_focus_in_sidebar(self):%0A    self.window.run_command(%22reveal_in_side_bar%22)%0A    self.window.run_command(%22focus_side_bar%22)%0A
 %0Aclass F
@@ -1275,24 +1275,58 @@
 _visible():%0A
+            refresh_folders(self)%0A
             
@@ -1379,228 +1379,171 @@
     
-self.window.run_command(%22reveal_in_side_bar%22)%0A            # Without the timeout the command on the palette doesn't work%0A            sublime.set_timeout(%0A                lambda: self.window.run_command('
+# set_project_data is asynchronous so we need settimeout for subsequent commands%0A            sublime.set_timeout_async(lambda: reveal_and_
 focus_
+in_
 side
-_
 bar
-'
+(self
 ), 
+2
 50)%0A
@@ -1670,36 +1670,8 @@
     
- sublime.set_timeout(lambda:
  ref
@@ -1692,13 +1692,8 @@
 elf)
-, 50)
 %0A   
@@ -1727,108 +1727,116 @@
     
-self.window.run_command(%22reveal_in_side_bar%22)%0A                self.window.run_command('
+refresh_folders(self)%0A                sublime.set_timeout_async(lambda: reveal_and_
 focus_
+in_
 side
-_
 bar
-'
+(self), 250
 )%0A

refresh project folder and focus when sidebar is open (#23)