import React from 'react';
import PropTypes from 'prop-types';
import IDUtil from '../../../../util/IDUtil';
import classNames from 'classnames';
import Metadataform from '../MetadataForm';

class Metadata extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            edit: false
        };
    }

    delete = e => {
        e.preventDefault();
        if (confirm('Are you sure you want to delete this metadata?')) {
            this.props.delete(this.props.metadata);
        }
    };

    toggleEdit = e => {
        this.setState({ edit: !this.state.edit });
    };

    render() {
        const componentClass = classNames(IDUtil.cssClassName('metadata-type'));
        const metadata = this.props.metadata;
        if (!metadata) {
            return null;
        }

        // Edit mode
        if (this.state.edit) {
            return (
                <div className={classNames(componentClass, 'edit')}>
                    <Metadataform
                        onSave={this.toggleEdit}
                        annotationClient={this.props.annotationClient}
                        annotation={this.props.targetAnnotation}
                        card={metadata}
                    />
                </div>
            );
        }

        // View mode

        // format date string
        const created = (metadata.created || '').replace('T', ' ').slice(0, -4);

        // render fields
        const fields = metadata.properties.map((property, index) => (
            <li key={index}>
                <strong>{property.key}</strong> <span>{property.value}</span>
            </li>
        ));

        return (
            <div className={componentClass} onDoubleClick={this.toggleEdit}>
                <div className="delete" title="Delete" onClick={this.delete} />
                <ul>{fields}</ul>
                <span className="template">{metadata.annotationTemplate}</span>
                <span className="created">{created}</span>
            </div>
        );
    }
}

Metadata.propTypes = {
    metadata: PropTypes.object,
    delete: PropTypes.func.isRequired,
    annotationClient: PropTypes.object.isRequired,
    targetAnnotation: PropTypes.object.isRequired
};
export default Metadata;
