import * as React from 'react'
import { Input, Icon, notification } from 'antd'
import { Button } from 'antd'
import { targetToString } from '../../helpers'

import './index.less'

export interface IProps {
  name: string
  namespace?: string
  version?: string
}

export default class extends React.Component<IProps, any> {
  public render() {
    return (
      <div className="terminal-input">
        <Input
          ref="command"
          size="large"
          className="terminal-input"
          style={{ paddingTop: '10px' }}
          value={this.getCommand()}
          readOnly={true}
          addonAfter={
            <Button
              onClick={this.onClickCopy}
              className="copy-to-clipboard-btn"
            >
              <Icon type="copy" />
            </Button>
          }
        />
      </div>
    )
  }

  private onClickCopy = () => {
    const { command } = this.refs
    ;(command as any).select()
    document.execCommand('copy')
    ;(command as any).focus()

    notification.success({ message: 'Copied to clipboard!' })
  }

  private getCommand() {
    const { version, name, namespace } = this.props

    const target = targetToString({ name, namespace })

    const command = `openscript execute ${target}`

    if (version) {
      return `${command}@${version}`
    } else {
      return command
    }
  }
}
