import React from 'react'

const highlightTextNodes = (element, regex, termid) => {
  var tempinnerHTML = element.innerHTML
  // Do regex replace
  element.innerHTML = tempinnerHTML.replace(regex,">$1<span style='background-color : rgba(49, 116, 250, 0.3);'>$2</span>$3<")
}

const getSearchString = text => {
	return text
}

const highlightContent = (node,searchText) => {
	// if(!searchText.trim()) return
	var searchString = getSearchString(searchText)
	var searchTerms = [searchString]
	searchTerms.forEach((searchTerm,i)=>{
		// The regex is the secret, it prevents text within tag declarations to be affected
     	var regex = new RegExp(">([^<]*)?("+searchTerm+")([^>]*)?<","g")
     	highlightTextNodes(node, regex, i)
	})
}

export default class Highlighter extends React.Component{

	elRef = el =>{
		if(el){
			this.el = el
		}
	}

	render(){
		return(
			<div ref={this.elRef}>{this.props.renderContent}</div>
		)
	}

	componentDidUpdate(){
		highlightContent(this.el,this.props.searchText)
	}
}