import mergeWith from 'lodash.mergewith';
import { createContext, useContext } from 'react';

export type TableValue = {
    /** Make the head fixed as a user scrolls */
    sticky: boolean;

    /** Highlight rows on hover */
    highlight: boolean;

    /** Add strips to the rows */
    striped: boolean;

    /** Value to determine table cell */
    cellType: 'head' | 'body' | null;
};

/**
 * Grid Context
 */
export const TableContext = createContext<TableValue | undefined>(undefined);

/**
 * Access the current Table's context
 *
 * @param values - current values
 *
 * @returns the TableValue
 */
export function useTable(values: Partial<TableValue> = {}): TableValue {
    const context = useContext(TableContext);
    if (context === undefined) {
        throw new Error('useForm must be used within a Form');
    }

    // merge but ignore the undefined values
    const merged = mergeWith({}, context, values, (a, b) => {
        if (b === undefined) {
            return a;
        }
    });

    // merge the two options together with the values taking precence
    return merged;
}
