'use babel';

import url from 'url'
import { CompositeDisposable } from 'atom'
import MJMLView from './mjml-view'

let MJMLPaneView = null

export default {
  config: {
    triggerOnSave: {
      type: 'boolean',
      description: 'Update the preview on each save.',
      default: true,
    },
  },

  desactivate() {
    this.subscriptions.dispose()
  },

  activate() {
    this.subscriptions = new CompositeDisposable()
    this.subscriptions.add(atom.workspace.observeTextEditors((editor) => {
      this.subscriptions.add(editor.onDidSave(() => {
        if (atom.config.get('mjml-preview.triggerOnSave')) {
          this.openPane(editor)
        }
      }))
    }))

    atom.workspace.addOpener(this.mjmlPreviewOpener)

    this.keybindings()
  },

  keybindings() {
    this.subscriptions.add(atom.commands.add('atom-workspace', { 'mjml-preview:preview': () => this.openPane() }))
  },

  openPane(editor) {
    const currentEditor = editor || atom.workspace.getActiveTextEditor()

    if (!currentEditor) {
      // probably trying to render an mjml-preview pane
      return;
    }

    const uri = 'mjml-preview://file'
    const previewPane = atom.workspace.paneForURI(uri)
    const fileGrammar = currentEditor.getGrammar()

    if (fileGrammar.scopeName !== 'text.mjml.basic') {
      return;
    }

    if (previewPane) {
      previewPane.destroyItem(previewPane.itemForURI(uri))
    }

    atom.workspace.open(uri, { split: 'right', searchAllPanes: true }).then(() => MJMLPaneView.render(currentEditor))
  },

  mjmlPreviewOpener(uri) {
    try {
      const { protocol, pathname } = url.parse(uri)
      if (protocol !== 'mjml-preview:') {
        return;
      }

      const filePath = decodeURI(pathname)

      MJMLPaneView = new MJMLView(filePath)

      return MJMLPaneView
    } catch (e) {
      return;
    }
  },
}

@@ -1395,24 +1395,87 @@
 ri))%0A    %7D%0A%0A
+    const previousActivePane = atom.workspace.getActivePane()%0A%0A
     atom.wor
@@ -1580,16 +1580,65 @@
 ditor))%0A
+      .done(() =%3E previousActivePane.activate())%0A
   %7D,%0A%0A  

return focus after creating a preview pane