import React, { Component } from 'react'
import { Button, message as Message, Space } from 'antd'
import MonacoEditor from 'react-monaco-editor'

const baseCopy = content => {
    try {
        const $textarea = document.createElement('textarea')
        $textarea.style = 'opacity: 0;position: fixed;top: -10000;left: -10000'
        document.body.append($textarea)
        $textarea.value = content
        $textarea.select()
        document.execCommand('copy')
        $textarea.remove()
        Message.success('已复制到剪贴板')
    } catch {
        Message.error('复制失败')
    }
}

const copy = code => {
    baseCopy(code)
}

const copyTemplate = code => {
    code =
        '"' +
        code
            // 转义双引号 => \"
            .replace(/"/g, '\\"')
            // 转义$ => $$
            .replace(/\$/g, '$$$$')
            // 替换行首 => "
            .replace(/\n/g, '"')
            // 替换行末 = ",
            .replace(/\r/g, '",\r') +
        '"'
    let flag = true
    while (flag) {
        const p = code.match(/\$\${.*?}/)
        if (p && p[0]) {
            code = code.replace(p[0], `$\{${p[0].slice(1)}}`)
        } else {
            flag = false
        }
    }
    baseCopy(code)
}

export default class highlighter extends Component {
    onEditorDidMount(editor) {
        editor.setValue(this.props.code)
    }

    render() {
        const { code, copyTemplate } = this.props

        const line = code.split('\r\n').length
        const height = line > 20 ? 400 : line * 20

        return (
            <section>
                <MonacoEditor
                    height={height}
                    {...this.props}
                    theme="vs-dark"
                    options={{
                        fontSize: 12,
                        readOnly: true,
                        lineHeight: 20,
                    }}
                    editorDidMount={editor => this.onEditorDidMount(editor)}
                />
                <div className="text-right mt-sm">
                    <Space>
                        {copyTemplate && (
                            <Button size="small" type="dashed" onClick={() => copyTemplate(code)}>
                                Copy template
                            </Button>
                        )}
                        <Button size="small" type="dashed" onClick={() => copy(code)}>
                            Copy
                        </Button>
                    </Space>
                </div>
            </section>
        )
    }
}
