Check TOC for headers and hide if TOC is empty

Hello i use this panel with this code

to show table of content in sidebar.
But i don’t know how hide panel header and footer if the page hasn’t headers (TOC is empty).
Can any body help me?

may be it will helps somebody. I use this panel in right panel with my custom css style. When page has not headers, TOC are not showing.

{{velocity}}
{{context document="$services.model.serialize($doc.documentReference)" transformationContext="document"}}
#set ($hasHeaders = [])
#set ($mydoc = $doc.getDocument())
#foreach ($block in $mydoc.getXDOM().getBlocks('class:HeaderBlock', 'DESCENDANT'))
 #set ($discard = $hasHeaders.add($block))
#end
{{/context}}
#if($hasHeaders.size()>0)
 #panelheader('Table of Contents')
#end
{{context document="$services.model.serialize($doc.documentReference)" transformationContext="document"}}
{{box cssClass="righttoc"}}{{toc/}}{{/box}}
{{/context}}
{{/velocity}}