import React from "react";
import PropTypes from "prop-types";
import classNames from "classnames";

import IDUtil from "../../../util/IDUtil";

import SegmentHeader from "./SegmentHeader";
import { renderPerType, getAnnotationsPerType } from "../AnnotationHelpers";
import { MSAnnotationUtil } from "../AnnotationClient";
import { ANNOTATION_COLUMN_SEGMENT_ID } from "../../../util/AnnotationConstants";

export default class Segment extends React.PureComponent {
    constructor(props) {
        super(props);

        this.state = {
            active: false,
        };
    }

    onSelectSegment = (segment) => {
        this.props.annotationClient.setActiveAnnotation(segment);

        // Selection
        const selection = MSAnnotationUtil.extractSelectionFromTarget(
            segment.target
        );
        if (!selection) {
            console.warn("could not extract selection from segment", segment);
            return;
        }
        this.props.annotationClient.setActiveSelection(selection);
    };

    toggle = () => {
        this.setState({ active: !this.state.active });
    };

    render() {
        // header
        const header = (
            <SegmentHeader
                segment={this.props.segment}
                active={this.state.active}
                onToggle={this.toggle}
                onSelect={this.onSelectSegment}
                updateSegment={this.props.updateSegment}
                activeTypes={this.props.activeTypes}
                highlight={
                    this.props.annotationClient.activeAnnotation &&
                    this.props.annotationClient.activeAnnotation.id ==
                        this.props.segment.id
                        ? true
                        : false
                }
            />
        );

        // types
        const types = this.state.active
            ? renderPerType(
                  getAnnotationsPerType(
                      this.props.activeTypes,
                      this.props.segment
                  ),
                  this.props.target,
                  this.props.segment,
                  this.props.annotationClient,
                  this.props.activeTypes,
                  false // hide forms by default
              )
            : null;

        return (
            <div
                className={classNames(IDUtil.cssClassName("segment"))}
                id={ANNOTATION_COLUMN_SEGMENT_ID + this.props.segment.id}
            >
                {header}
                {types}
            </div>
        );
    }
}

Segment.propTypes = {
    annotationClient: PropTypes.object.isRequired,
    activeTypes: PropTypes.arrayOf(PropTypes.string).isRequired,
    segment: PropTypes.object.isRequired,
    target: PropTypes.string.isRequired,
    updateSegment: PropTypes.func.isRequired,
};
