import * as React from 'react';
import './CodeBox.css';
import {filter, Render} from '../../render/index';
import {Tooltip} from '@native-ads/antd';
import {HighLight} from '../common/HighLight';

let unExpand = require('./img/unExpand.svg');
let expanded = require('./img/expanded.svg');

// test only
function toUpperCase(word: string) {
    return word.toUpperCase();
}

filter.setFilter('toUpperCase', toUpperCase);

export interface CodeBoxPropsInterface {
    title: string;
    desc: string;
    code: string;
    language: string;
    mode?: string;
}

export interface CodeBoxStateInterface {
    expand: boolean;
}

export class CodeBox extends React.Component<CodeBoxPropsInterface, CodeBoxStateInterface> {
    constructor(props: CodeBoxPropsInterface) {
        super(props);

        this.state = {
            expand: false
        };

        this.handleClick = this.handleClick.bind(this);
    }

    render() {
        const global = {
            text: 'this is global value',
            proxy: location.origin + '/proxy'
        };
        return (
            <div className="codebox">
                <div className={'codebox-' + this.props.mode}>
                    <Render code={this.props.code} global={global} />
                </div>
                <div className="codebox-markdown">
                    {this.props.title && <div className="codebox-title">{this.props.title}</div>}
                    {
                        this.props.desc &&
                        <div className="codebox-content" dangerouslySetInnerHTML={{__html: this.props.desc}}/>
                    }
                    <span className="expand-icon" onClick={this.handleClick}>
                    <Tooltip title="show code">
                        <img style={{display: !this.state.expand ? 'block' : 'none'}} src={unExpand}/>
                    </Tooltip>
                    <Tooltip title="hide code">
                        <img style={{display: this.state.expand ? 'block' : 'none'}} src={expanded}/>
                    </Tooltip>
                </span>
                </div>
                <div style={{display: this.state.expand ? 'block' : 'none'}} className="codeblock-wrapper">
                    <HighLight className={this.props.language}>
                        {this.props.code.trim()}
                    </HighLight>
                </div>
            </div>
        );
    }

    private handleClick() {
        this.setState({
            expand: !this.state.expand
        });
    }
}
