import $ from 'jquery'
import 'vendor/jquery.caret'
import caretToEnd from 'caret-to-end'
import * as At from 'lib/at'
import React from 'react'
import ReactDOM from 'react-dom'
import * as Types from 'types'
import * as Commands from 'components/commands'

class Field {

  constructor($element) {
    this.$element = $element
    this.listen = this.listen.bind(this)
  }

  observe() {
    At.setup(this.$element)
    this.$element.on('keyup', this.listen)
    this.$element.on('blur', (e) => {
      this.$element.off('keup', this.listen)
    })
  }

  listen() {
    let { command, match } = Commands.match(this.getText())
    if (command) {
      this.mount(command, match)
    }
  }

  getText() {
    throw new Error('Not implemented')
  }

  replaceText(text) {
    throw new Error('Not implemented')
  }

  setText(text) {
    throw new Error('Not implemented')
  }

  appendText(text) {
    this.setText(this.getText() + text)
  }

  getCaretOffset() {
    return this.$element.caret('offset')
  }

  focus() {
    caretToEnd(this.$element[0])
  }

  onBlur() {
    this.$element.off('keyup', this.listen)
  }

  mount(Component, match) {
      this.replaceText(match, "")

      let $container = this.getContainer()
      let caretOffset = this.getCaretOffset()
      let onDone = (result) => {
        this.add(result)
        ReactDOM.unmountComponentAtNode($container[0])
        this.focus()
      }

      ReactDOM.render(
        <Component
          $element={this.$element}
          top={caretOffset.top}
          left={caretOffset.left}
          onDone={onDone}
        />,
        $container[0]
      )
  }

  getContainer() {
    let $container = $('.slash__container')
    if (!$container.length) {
      $container = $('<div>')
        .addClass('slash__container')
        .appendTo('body')
    }
    return $container
  }

  add(type) {
    if (!type) return

    let fnName = `add${type.constructor.name}`
    return this[fnName](type)
  }

  addImage(image) {
    throw new Error('Not implemented')
  }

  addRedirect(redirect) {
    window.open(redirect.url, redirect.target)
  }


}

export default Field

@@ -1890,80 +1890,229 @@
     
-let fnName = %60add$%7Btype.constructor.name%7D%60%0A    return this%5BfnName%5D(type)
+switch (type.constructor) %7B%0A      case Types.Image:%0A        return this.addImage(type)%0A      case Types.Redirect:%0A        return this.addRedirect(type)%0A      default:%0A        throw new Error(%22Not implemented error%22)%0A    %7D
 %0A  %7D
@@ -2254,14 +2254,12 @@
 et)%0A
+
   %7D%0A
-%0A%0A
 %7D%0A%0Ae

fix issue caused by minification of transform functions