import React, { Component, PropTypes } from 'react';
import webFragments from 'bitbucket/internal/impl/web-fragments';
import prUniqueId from '../../utils/pull-request-unique-id';

export const beforeSections = webFragments.getWebSections('bitbucket.pull-request.table-column.before');
export const afterSections = webFragments.getWebSections('bitbucket.pull-request.table-column.after');

export const WebSectionHeader = props => {
    const webSection = props.webSection;
    return (
        <th
            className={webSection.key + " web-section-column"}
            title={webSection.text}
            scope="col"
        >
            {webSection.text}
        </th>
    );
};

WebSectionHeader.propTypes = {
    webSection: PropTypes.object.isRequired,
};

export class WebSectionCell extends Component {
    // We don't want to regrab the web panels for existing rows every time the table rerenders as this would cause them to needlessly
    // redo their work. So we only regrab them when the props actually change. This component is used with a React key={} prop,
    // and in theory each row should only render once ever.
    shouldComponentUpdate(newProps) {
        return prUniqueId(newProps.pullRequest) !== prUniqueId(this.props.pullRequest) ||
            newProps.webSection.key !== this.props.webSection.key ||
            newProps.where !== this.props.where;
    }

    render() {
        const webSection = this.props.webSection;
        const pullRequest = this.props.pullRequest;
        const location = `bitbucket.pull-request.table-column.${this.props.where}/${webSection.key}`;
        return (
            <td
                className={webSection.key + "-value web-section-column"}
                dangerouslySetInnerHTML={{
                    __html: webFragments.getWebPanels(location, { pullRequest }).map(p => p.html).join(''),
                }}
            />
        );
    }
}

WebSectionCell.propTypes = {
    pullRequest: PropTypes.object.isRequired,
    webSection: PropTypes.object.isRequired,
    where: PropTypes.string.isRequired,
};

export default {
    afterSections,
    beforeSections,
    WebSectionHeader,
    WebSectionCell,
};
