import {RawHTML} from "../RawHTML";
import React, {MouseEvent} from "react";
import {SectionItem} from "./Data";

const elemTypes = ['iframe', 'input', 'textarea', 'button', 'select'];

interface FormTableProps {
    sectionItem: SectionItem,
    visible?: boolean,
    onElementClick?: ((elem: Element) => void),
}

export const FormTable = ({sectionItem, onElementClick, visible=true}: FormTableProps) => 
{    
    const hiddenElemSelector = Object.entries(sectionItem.configSettings)
        .map(([key, data]) => data.visible ? null : key)
        .filter(Boolean)
        .map(key => '#' + key)
        .join(', ')
    ;
    
    Object.values(sectionItem.configSettings)
        .filter(cfgObj => !cfgObj.visible)
        .map(cfgObj => cfgObj.html)
        .join('');
    
    return <>
        <RawHTML hide={!visible} onClick={(e: MouseEvent) => {
            const elem = e.target as Element;
            if (elemTypes.includes(elem.tagName.toLowerCase()) && onElementClick) {
                onElementClick(elem);
            }
        }}> 
        {
            sectionItem.tableOpen + renderSectionRows(sectionItem) + sectionItem.tableClose
        } 
        </RawHTML>
        <style>{`
            .search-applied :is(${hiddenElemSelector}) { 
                display: none !important;
            }
        `}    
        </style>
    </>;
}

// todo rcp Improve search box style (firefox clear button)
function renderSectionRows(section: SectionItem): string 
{
    return Object.values(section.configSettings)
        // .filter(cfgObj => cfgObj.visible)
        .map(cfgObj => cfgObj.html)
        .join('');
}