import * as React from 'react'

import './index.less'

interface Props {
  asset: { content: string }
  readOnly?: boolean
}

interface State {
  value: string | null
}

export default class extends React.Component<Props, State> {
  state: State = { value: null }

  render() {
    return (
      <div id="code-editor" style={{ width: '100%', height: '600px' }}>
        <textarea className="component-code-editor" value={this.getValue()} />
      </div>
    )
  }

  private getValue = () => {
    const {
      asset: { content },
    } = this.props
    const value = new Buffer(content, 'base64').toString()
    return value
  }

  private mountEditor = async (props: Props) => {
    const containerElement = document.getElementById('code-editor')
    containerElement.innerHTML = ''
    const monaco = await import('monaco-editor')
    monaco.editor.create(containerElement, {
      readOnly: props.readOnly || false,
      value: this.getValue(),
      theme: 'vs-dark',
      language: 'shell',
    })
  }

  async componentDidMount() {
    this.mountEditor(this.props)
  }

  async componentDidUpdate() {
    this.mountEditor(this.props)
  }
}
