import React from 'react';
import ReactTooltip from 'react-tooltip';

export default class Tooltip extends React.Component {

    constructor(props) {
        super(props);
    }

    hashCode = function(str) {
        let hash = 0, i, chr, len;
        if (str && (str.length === 0)) return hash;
        if(!str) return hash;
        for (i = 0, len = str.length; i < len; i++) {
            chr   = str.charCodeAt(i);
            hash  = ((hash << 5) - hash) + chr;
            hash |= 0; // Convert to 32bit integer
        }
        return hash;
    };

    //TODO: Remove tooltip prefixes.
    static get PropTypes(){
        return {
            tooltipTitle: React.PropTypes.string,
            tooltipText: React.PropTypes.string,
            hoverElement: React.PropTypes.object
        }
    }

    getTooltipTemplate = () => {
    let title = this.props.tooltipTitle ?`<h3>${this.props.tooltipTitle}</h3>` : '',
    text = this.props.tooltipText;
    return `<div class="tooltip-container">${title}<div class="tooltip-text">${text}</div></div>`;
    };

    onMouseEnter = () => {
      if(this.props.callBack) {
        this.props.callBack();
      }
    }

    renderTooltip = (id) => {
      if(this.props.component) {
        var Component = this.props.component;
        return (
          <div>
            <div style={{display:'inline-block'}} className='title' data-for={id} data-tip>
                {this.props.hoverElement}
            </div>
            <ReactTooltip id={id} effect='solid' getContent={[() => <Component {...this.props} />]} place={this.props.place || "top"} />
          </div>
        )
      }
      else {
        return (
          <div>
            <div  style={{display:'inline-block'}} className='title' data-multiline={true} data-for={id} data-html={true} data-tip={this.getTooltipTemplate()}>
                {this.props.hoverElement}
            </div>
            <ReactTooltip id={id} html={true} effect='solid' place={this.props.place || "top"} />
          </div>
        )
      }
    }

    render() {
        if(this.props && this.props.hoverElement) {
            const id = this.props.id ? this.props.id : `tooltip-${this.hashCode(this.props.tooltipText)}`;
            return (
                <div style={{display:'inline-block'}} onMouseEnter={this.onMouseEnter} className={(this.props.className?this.props.className:'')}>
                  {this.renderTooltip(id)}
                </div>
            );
        } else {
        return null;
        }
    }
    }
