import { jsx } from "react/jsx-runtime";
import { createContext, useContext, useState } from "react";
import { App } from "antd";
import { useTranslation } from "react-i18next";
import { useAPIClient } from "../../../api-client/index.mjs";
import { useRecord } from "../../../record-provider/index.mjs";
const SettingCenterPermissionProvider = (props)=>{
    var _currentRecord_snippets;
    const { currentRecord } = useContext(PermissionContext);
    if (!(null == currentRecord ? void 0 : null == (_currentRecord_snippets = currentRecord.snippets) ? void 0 : _currentRecord_snippets.includes('pm.*'))) return null;
    return /*#__PURE__*/ jsx("div", {
        children: props.children
    });
};
const PermissionContext = /*#__PURE__*/ createContext(null);
PermissionContext.displayName = 'PermissionContext';
const PermissionProvider = (props)=>{
    const api = useAPIClient();
    const record = useRecord();
    const { t } = useTranslation();
    const { message } = App.useApp();
    const { snippets } = record;
    null == snippets || snippets.forEach((key)=>{
        record[key] = true;
    });
    const [currentRecord, setCurrentRecord] = useState(record);
    return /*#__PURE__*/ jsx(PermissionContext.Provider, {
        value: {
            currentRecord,
            update: async (field, form)=>{
                const { path, value } = field.getState();
                if ([
                    'ui.*',
                    'pm',
                    'pm.*'
                ].includes(path)) {
                    const resource = api.resource('roles.snippets', record.name);
                    if (value) await resource.add({
                        values: [
                            path
                        ]
                    });
                    else await resource.remove({
                        values: [
                            path
                        ]
                    });
                    setCurrentRecord({
                        ...currentRecord,
                        ...form.values,
                        [path]: value
                    });
                } else {
                    await api.resource('roles').update({
                        filterByTk: record.name,
                        values: form.values
                    });
                    setCurrentRecord({
                        ...currentRecord,
                        ...form.values
                    });
                }
                message.success(t('Saved successfully'));
            }
        },
        children: props.children
    });
};
export { PermissionContext, PermissionProvider, SettingCenterPermissionProvider };
