import React from "react";
import PropTypes from "prop-types";
import IDUtil from "../../util/IDUtil";

class EditableText extends React.Component {
    constructor(props) {
        super();
        this.state = {
            edit: false,
        };
        this.ref = React.createRef();
    }

    onKeyPress = (e) => {
        switch (e.key) {
            case "Enter": // enter
                this.save();
                break;
        }
    };

    save = async () => {
        if (!this.ref.current) {
            return;
        }

        await this.props.onChange(this.ref.current.value);

        // stop edit mode
        this.setState({
            edit: false,
        });
    };

    edit = () => {
        this.setState({ edit: true });
    };

    componentDidUpdate(_, prevState) {
        if (prevState.edit != this.state.edit) {
            if (this.ref.current) {
                this.ref.current.focus();
                this.ref.current.select();
            }
        }
    }

    render() {
        // label
        if (!this.state.edit) {
            return (
                <span
                    className={IDUtil.cssClassName("editable-text")}
                    onClick={(e) => {
                        e.stopPropagation();
                    }}
                    onDoubleClick={this.edit}
                >
                    {this.props.value}
                </span>
            );
        }

        // edit
        return (
            <input
                className={IDUtil.cssClassName("editable-text")}
                ref={this.ref}
                defaultValue={this.props.value}
                type="text"
                onBlur={this.save}
                onKeyPress={this.onKeyPress}
            />
        );
    }
}

EditableText.propTypes = {
    value: PropTypes.string.isRequired,
    onChange: PropTypes.func.isRequired,
};

export default EditableText;
