import { WidgetPropsWithChildren } from "@insite/client-framework/Types/WidgetProps";
import ShellState from "@insite/shell/Store/ShellState";
import ShellThunkAction from "@insite/shell/Store/ShellThunkAction";

export const copyWidget =
    (id: string): ShellThunkAction =>
    (dispatch, getState) => {
        const state = getState();
        const widget = {
            ...state.data.pages.widgetsById[id],
            children: getWidgetChildren(state, id),
        };

        dispatch({
            type: "Clipboard/CopyWidget",
            widget,
        });
    };

export const clearClipboardWidget = (): ShellThunkAction => dispatch => {
    dispatch({
        type: "Clipboard/ClearWidget",
    });
};

const getWidgetChildren = (state: ShellState, id: string): WidgetPropsWithChildren[] => {
    const children = Object.values(state.data.pages.widgetsById).filter(o => o.parentId === id);
    return children.map(o => ({ ...o, children: getWidgetChildren(state, o.id) }));
};
