import { Tool, domHelpers } from 'substance'

/*
  Tool to edit math markup.
*/
export default class EditInlineFormulaTool extends Tool {

  getNodeId() {
    return this.props.commandState.nodeId
  }

  getSourcePath() {
    const nodeId = this.props.commandState.nodeId
    const inlineFormula = this.context.editorSession.getDocument().get(nodeId)
    const texMath = inlineFormula._childNodes[0]
    return [ texMath ].concat('textContent')
  }

  render($$) {
    let Input = this.getComponent('input')
    let commandState = this.props.commandState
    let el = $$('div').addClass('sc-edit-math-tool')

    // GUARD: Return if tool is disabled
    if (commandState.disabled) {
      console.warn('Tried to render EditMathTool while disabled.')
      return el
    }

    let sourcePath = this.getSourcePath()

    el.append(
      $$(Input, {
        type: 'text',
        path: sourcePath,
        placeholder: 'Enter TeX'
      })
      // ATTNETION have a ref on it, otherwise the input will get rerendered on every change
      .ref('input')
      // stopping keydown events so that the input field is not distracted by other editor keyboard handler
      // TODO: maybe let 'Save' through...
      .on('keydown', domHelpers.stop)
    )
    return el
  }

  onDelete(e) {
    e.preventDefault();
    let nodeId = this.getNodeId()
    let sm = this.context.surfaceManager
    let surface = sm.getFocusedSurface()
    if (!surface) {
      console.warn('No focused surface. Stopping command execution.')
      return
    }
    let editorSession = this.context.editorSession
    editorSession.transaction((tx, args) => {
      tx.delete(nodeId)
      return args
    })
  }
}

@@ -225,22 +225,28 @@
   const 
-nodeId
+commandState
  = this.
@@ -263,23 +263,16 @@
 andState
-.nodeId
 %0A    con
@@ -274,29 +274,19 @@
   const 
-inlineFormula
+doc
  = this.
@@ -320,16 +320,85 @@
 cument()
+%0A    const nodeId = commandState.nodeId%0A    const inlineFormula = doc
 .get(nod
@@ -419,16 +419,18 @@
  texMath
+Id
  = inlin
@@ -477,32 +477,23 @@
 Math
- %5D.concat('textC
+Id, 'c
 ontent'
-)
+ %5D
 %0A  %7D
@@ -816,17 +816,16 @@
 l%0A    %7D%0A
-%0A
     let 
@@ -858,17 +858,16 @@
 ePath()%0A
-%0A
     el.a

Fix bug in EditInlineFormulaTool