import sublime, sublime_plugin
import desktop
import tempfile
import markdown
import os
import re


def getTempMarkdownPreviewPath(view):
    " return a permanent full path of the temp markdown preview file "
    tmp_filename = '%s.html' % view.id()
    tmp_fullpath = os.path.join(tempfile.gettempdir(), tmp_filename)
    return tmp_fullpath


class MarkdownPreviewListener(sublime_plugin.EventListener):
    """ update the output html when markdown file has already been converted once """

    def on_post_save(self, view):
        if view.file_name().endswith(('.md', '.markdown', '.mdown')):
            temp_file = getTempMarkdownPreviewPath(view)
            if os.path.isfile(temp_file):
                # reexec markdown conversion
                view.run_command('markdown_preview', {'target': 'disk'})


class MarkdownPreviewCommand(sublime_plugin.TextCommand):
    """ preview file contents with python-markdown and your web browser"""

    def getCSS(self):
        css_filename = 'markdown.css'
        # path via package manager
        css_path = os.path.join(sublime.packages_path(), 'Markdown Preview', css_filename)
        if not os.path.isfile(css_path):
            # path via git repo
            css_path = os.path.join(sublime.packages_path(), 'sublimetext-markdown-preview', css_filename)
            if not os.path.isfile(css_path):
                raise Exception("markdown.css file not found!")

        return open(css_path, 'r').read().decode('utf-8')

    def postprocessor(self, html):
        # fix relative images paths
        def img_fix(match):
            img, src = match.groups()
            filename = self.view.file_name()
            if filename:
                if not src.startswith(('file://', 'https://', 'http://', '/')):
                    abs_path = u'file://%s/%s' % (os.path.dirname(filename), src)
                    img = img.replace(src, abs_path)
            return img
        RE_IMGS = re.compile("""(?P<img><img[^>]+src=["'](?P<src>[^"']+)[^>]*>)""")
        html = RE_IMGS.sub(img_fix, html)
        return html

    def run(self, edit, target='browser'):
        region = sublime.Region(0, self.view.size())
        encoding = self.view.encoding()
        if encoding == 'Undefined':
            encoding = 'utf-8'
        elif encoding == 'Western (Windows 1252)':
            encoding = 'windows-1252'
        contents = self.view.substr(region)

        # convert the markdown
        markdown_html = markdown.markdown(contents)

        # postprocess the html
        markdown_html = self.postprocessor(markdown_html)
        # check if LiveReload ST2 extension installed
        livereload_installed = ('LiveReload' in os.listdir(sublime.packages_path()))

        # build the html
        html_contents = u'<!DOCTYPE html>'
        html_contents += '<html><head><meta charset="%s">' % encoding
        styles = self.getCSS()
        html_contents += '<style>%s</style>' % styles
        if livereload_installed:
            html_contents += '<script>document.write(\'<script src="http://\' + (location.host || \'localhost\').split(\':\')[0] + \':35729/livereload.js?snipver=1"></\' + \'script>\')</script>'
        html_contents += '</head><body>'
        html_contents += markdown_html
        html_contents += '</body>'

        if target in ['disk', 'browser']:
            # update output html file
            tmp_fullpath = getTempMarkdownPreviewPath(self.view)
            tmp_html = open(tmp_fullpath, 'w')
            tmp_html.write(html_contents.encode(encoding))
            tmp_html.close()
            # todo : livereload ?
            if target == 'browser':
                desktop.open(tmp_fullpath)
        elif target == 'sublime':
            new_view = self.view.window().new_file()
            new_edit = new_view.begin_edit()
            new_view.insert(new_edit, 0, html_contents)
            new_view.end_edit(new_edit)
        print 'markdown converted'

@@ -1540,19 +1540,30 @@
 ive 
-images path
+paths in images/script
 s%0A  
@@ -1572,18 +1572,18 @@
     def 
-im
+ta
 g_fix(ma
@@ -1600,18 +1600,18 @@
         
-im
+ta
 g, src =
@@ -1882,16 +1882,16 @@
     
-im
+ta
 g = 
-im
+ta
 g.re
@@ -1930,18 +1930,18 @@
  return 
-im
+ta
 g%0A      
@@ -1945,19 +1945,22 @@
      RE_
-IMG
+SOURCE
 S = re.c
@@ -1977,16 +1977,27 @@
 (?P%3C
-img%3E%3Cimg
+tag%3E%3C(?:img%7Cscript)
 %5B%5E%3E%5D
@@ -2054,19 +2054,22 @@
  RE_
-IMG
+SOURCE
 S.sub(
-im
+ta
 g_fi
@@ -2604,24 +2604,25 @@
 kdown_html)%0A
+%0A
         # ch

replace relative scripts paths - fix #22