import * as __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__ from "react/jsx-runtime";
import * as __WEBPACK_EXTERNAL_MODULE_react__ from "react";
import * as __WEBPACK_EXTERNAL_MODULE__tachybase_schema__ from "@tachybase/schema";
import * as __WEBPACK_EXTERNAL_MODULE_lodash__ from "lodash";
import * as __WEBPACK_EXTERNAL_MODULE_react_router_dom__ from "react-router-dom";
import * as __WEBPACK_EXTERNAL_MODULE__api_client_index_mjs__ from "../../api-client/index.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__application_index_mjs__ from "../../application/index.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__block_provider_BlockProvider_mjs__ from "../../block-provider/BlockProvider.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__collection_manager_index_mjs__ from "../../collection-manager/index.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__collection_manager_ResourceActionProvider_mjs__ from "../../collection-manager/ResourceActionProvider.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__data_source_data_source_DataSourceProvider_mjs__ from "../../data-source/data-source/DataSourceProvider.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__record_provider_index_mjs__ from "../../record-provider/index.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__schema_component_index_mjs__ from "../../schema-component/index.mjs";
const ACLContext = /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react__.createContext)({});
ACLContext.displayName = 'ACLContext';
const ACLProvider = (props)=>/*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__schema_component_index_mjs__.SchemaComponentOptions, {
        components: {
            ACLCollectionFieldProvider,
            ACLActionProvider,
            ACLMenuItemProvider,
            ACLCollectionProvider
        },
        children: props.children
    });
const getRouteUrl = (props)=>{
    var _props_children;
    if (null == props ? void 0 : props.match) return props.match;
    return props && getRouteUrl(null == props ? void 0 : null === (_props_children = props.children) || void 0 === _props_children ? void 0 : _props_children.props);
};
const ACLRolesCheckProvider = (props)=>{
    getRouteUrl(props.children.props);
    const { setDesignable } = (0, __WEBPACK_EXTERNAL_MODULE__schema_component_index_mjs__.useDesignable)();
    const api = (0, __WEBPACK_EXTERNAL_MODULE__api_client_index_mjs__.useAPIClient)();
    const app = (0, __WEBPACK_EXTERNAL_MODULE__application_index_mjs__.useApp)();
    const result = (0, __WEBPACK_EXTERNAL_MODULE__api_client_index_mjs__.useRequest)({
        url: 'roles:check'
    }, {
        onSuccess (data) {
            var _data_data, _data_data1, _data_data2;
            if (!(null == data ? void 0 : null === (_data_data = data.data) || void 0 === _data_data ? void 0 : _data_data.snippets.includes('ui.*'))) setDesignable(false);
            if ((null == data ? void 0 : null === (_data_data1 = data.data) || void 0 === _data_data1 ? void 0 : _data_data1.role) !== api.auth.role) {
                var _data_data3;
                api.auth.setRole(null == data ? void 0 : null === (_data_data3 = data.data) || void 0 === _data_data3 ? void 0 : _data_data3.role);
            }
            app.systemSettingsManager.setAclSnippets((null == data ? void 0 : null === (_data_data2 = data.data) || void 0 === _data_data2 ? void 0 : _data_data2.snippets) || []);
        }
    });
    if (result.loading) return;
    if (result.error) return /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_react_router_dom__.Navigate, {
        replace: true,
        to: '/signin'
    });
    return /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(ACLContext.Provider, {
        value: result,
        children: props.children
    });
};
const useRoleRecheck = ()=>{
    const ctx = (0, __WEBPACK_EXTERNAL_MODULE_react__.useContext)(ACLContext);
    const { allowAll } = useACLRoleContext();
    return ()=>{
        if (allowAll) return;
        ctx.refresh();
    };
};
const useACLContext = ()=>(0, __WEBPACK_EXTERNAL_MODULE_react__.useContext)(ACLContext);
const ACLActionParamsContext = /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react__.createContext)({});
ACLActionParamsContext.displayName = 'ACLActionParamsContext';
const useACLRolesCheck = ()=>{
    var _ctx_data, _ctx_data1;
    const ctx = (0, __WEBPACK_EXTERNAL_MODULE_react__.useContext)(ACLContext);
    const dataSourceName = (0, __WEBPACK_EXTERNAL_MODULE__data_source_data_source_DataSourceProvider_mjs__.useDataSourceKey)();
    const { dataSources: dataSourcesAcl } = (null == ctx ? void 0 : null === (_ctx_data = ctx.data) || void 0 === _ctx_data ? void 0 : _ctx_data.meta) || {};
    const data = {
        ...null == ctx ? void 0 : null === (_ctx_data1 = ctx.data) || void 0 === _ctx_data1 ? void 0 : _ctx_data1.data,
        ...(0, __WEBPACK_EXTERNAL_MODULE_lodash__.omit)(null == dataSourcesAcl ? void 0 : dataSourcesAcl[dataSourceName], 'snippets')
    };
    const getActionAlias = (actionPath)=>{
        var _data_actionAlias;
        const actionName = actionPath.split(':').pop();
        return (null == data ? void 0 : null === (_data_actionAlias = data.actionAlias) || void 0 === _data_actionAlias ? void 0 : _data_actionAlias[actionName]) || actionName;
    };
    return {
        data,
        getActionAlias,
        inResources: (resourceName)=>{
            var _data_resources_includes, _data_resources;
            return null == data ? void 0 : null === (_data_resources = data.resources) || void 0 === _data_resources ? void 0 : null === (_data_resources_includes = _data_resources.includes) || void 0 === _data_resources_includes ? void 0 : _data_resources_includes.call(_data_resources, resourceName);
        },
        getResourceActionParams: (actionPath)=>{
            var _data_actions, _data_actions1;
            const [resourceName] = actionPath.split(':');
            const actionAlias = getActionAlias(actionPath);
            return (null == data ? void 0 : null === (_data_actions = data.actions) || void 0 === _data_actions ? void 0 : _data_actions["".concat(resourceName, ":").concat(actionAlias)]) || (null == data ? void 0 : null === (_data_actions1 = data.actions) || void 0 === _data_actions1 ? void 0 : _data_actions1[actionPath]);
        },
        getStrategyActionParams: (actionPath)=>{
            var _data_strategy_actions, _data_strategy;
            const actionAlias = getActionAlias(actionPath);
            const strategyAction = null == data ? void 0 : null === (_data_strategy = data.strategy) || void 0 === _data_strategy ? void 0 : null === (_data_strategy_actions = _data_strategy.actions) || void 0 === _data_strategy_actions ? void 0 : _data_strategy_actions.find((action)=>{
                const [value] = action.split(':');
                return value === actionAlias;
            });
            return strategyAction ? {} : null;
        }
    };
};
const getIgnoreScope = function() {
    let options = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {};
    var _schema_xaclactionprops;
    const { schema, recordPkValue } = options;
    let ignoreScope = false;
    if (options.ignoreScope) ignoreScope = true;
    if (null == schema ? void 0 : schema['x-acl-ignore-scope']) ignoreScope = true;
    if (null == schema ? void 0 : null === (_schema_xaclactionprops = schema['x-acl-action-props']) || void 0 === _schema_xaclactionprops ? void 0 : _schema_xaclactionprops['skipScopeCheck']) ignoreScope = true;
    if (!recordPkValue) ignoreScope = true;
    return ignoreScope;
};
const useAllowedActions = ()=>{
    var _service_data_meta, _service_data;
    const service = (0, __WEBPACK_EXTERNAL_MODULE__collection_manager_ResourceActionProvider_mjs__.useResourceActionContext)();
    const result = (0, __WEBPACK_EXTERNAL_MODULE__block_provider_BlockProvider_mjs__.useBlockRequestContext)();
    var _result_allowedActions;
    return null !== (_result_allowedActions = null == result ? void 0 : result.allowedActions) && void 0 !== _result_allowedActions ? _result_allowedActions : null == service ? void 0 : null === (_service_data = service.data) || void 0 === _service_data ? void 0 : null === (_service_data_meta = _service_data.meta) || void 0 === _service_data_meta ? void 0 : _service_data_meta.allowedActions;
};
const useResourceName = ()=>{
    var _result_props, _result_props1, _result_service_defaultRequest, _result_service;
    const service = (0, __WEBPACK_EXTERNAL_MODULE__collection_manager_ResourceActionProvider_mjs__.useResourceActionContext)();
    const result = (0, __WEBPACK_EXTERNAL_MODULE__block_provider_BlockProvider_mjs__.useBlockRequestContext)() || {
        service
    };
    return (null == result ? void 0 : null === (_result_props = result.props) || void 0 === _result_props ? void 0 : _result_props.resource) || (null == result ? void 0 : null === (_result_props1 = result.props) || void 0 === _result_props1 ? void 0 : _result_props1.collection) || (null == result ? void 0 : null === (_result_service = result.service) || void 0 === _result_service ? void 0 : null === (_result_service_defaultRequest = _result_service.defaultRequest) || void 0 === _result_service_defaultRequest ? void 0 : _result_service_defaultRequest.resource);
};
function useACLRoleContext() {
    const { data, getActionAlias, inResources, getResourceActionParams, getStrategyActionParams } = useACLRolesCheck();
    const allowedActions = useAllowedActions();
    const { getCollectionJoinField } = (0, __WEBPACK_EXTERNAL_MODULE__collection_manager_index_mjs__.useCollectionManager_deprecated)();
    const verifyScope = (actionName, recordPkValue)=>{
        const actionAlias = getActionAlias(actionName);
        if (!Array.isArray(null == allowedActions ? void 0 : allowedActions[actionAlias])) return null;
        return allowedActions[actionAlias].includes(recordPkValue);
    };
    return {
        ...data,
        parseAction: function(actionPath) {
            let options = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : {};
            var _getCollectionJoinField;
            const [resourceName, actionName] = actionPath.split(':');
            const targetResource = (null == resourceName ? void 0 : resourceName.includes('.')) && (null === (_getCollectionJoinField = getCollectionJoinField(resourceName)) || void 0 === _getCollectionJoinField ? void 0 : _getCollectionJoinField.target);
            if (!getIgnoreScope(options)) {
                const r = verifyScope(actionName, options.recordPkValue);
                if (null !== r) return r ? {} : null;
            }
            if (null == data ? void 0 : data.allowAll) return {};
            if (inResources(targetResource)) return getResourceActionParams("".concat(targetResource, ":").concat(actionName));
            if (inResources(resourceName)) return getResourceActionParams(actionPath);
            return getStrategyActionParams(actionPath);
        }
    };
}
const ACLCollectionProvider = (props)=>{
    const { allowAll, parseAction } = useACLRoleContext();
    const schema = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.useFieldSchema)();
    if (allowAll) return props.children;
    const actionPath = (null == schema ? void 0 : schema['x-acl-action']) || props.actionPath;
    if (!actionPath) return props.children;
    const params = parseAction(actionPath, {
        schema
    });
    if (!params) return null;
    const [_, actionName] = actionPath.split(':');
    params.actionName = actionName;
    return /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(ACLActionParamsContext.Provider, {
        value: params,
        children: props.children
    });
};
const useACLActionParamsContext = ()=>(0, __WEBPACK_EXTERNAL_MODULE_react__.useContext)(ACLActionParamsContext);
const useRecordPkValue = ()=>{
    const { getPrimaryKey } = (0, __WEBPACK_EXTERNAL_MODULE__collection_manager_index_mjs__.useCollection_deprecated)();
    const record = (0, __WEBPACK_EXTERNAL_MODULE__record_provider_index_mjs__.useRecord)();
    const primaryKey = getPrimaryKey();
    return null == record ? void 0 : record[primaryKey];
};
const ACLActionProvider = (props)=>{
    const { template, writableView } = (0, __WEBPACK_EXTERNAL_MODULE__collection_manager_index_mjs__.useCollection_deprecated)();
    const recordPkValue = useRecordPkValue();
    const resource = useResourceName();
    const { parseAction } = useACLRoleContext();
    const schema = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.useFieldSchema)();
    let actionPath = schema['x-acl-action'];
    const editablePath = [
        'create',
        'update',
        'destroy',
        'importXlsx'
    ];
    if (!actionPath && resource && schema['x-action']) actionPath = "".concat(resource, ":").concat(schema['x-action']);
    if (!(null == actionPath ? void 0 : actionPath.includes(':'))) actionPath = "".concat(resource, ":").concat(actionPath);
    if (!actionPath) return /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.Fragment, {
        children: props.children
    });
    if (!resource) return /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.Fragment, {
        children: props.children
    });
    const params = parseAction(actionPath, {
        schema,
        recordPkValue
    });
    if (!params) return /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(ACLActionParamsContext.Provider, {
        value: params,
        children: props.children
    });
    if (editablePath.includes(actionPath) || editablePath.includes(null == actionPath ? void 0 : actionPath.split(':')[1])) {
        if ('view' !== template || writableView) return /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(ACLActionParamsContext.Provider, {
            value: params,
            children: props.children
        });
        return null;
    }
    return /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(ACLActionParamsContext.Provider, {
        value: params,
        children: props.children
    });
};
const useACLFieldWhitelist = ()=>{
    const params = (0, __WEBPACK_EXTERNAL_MODULE_react__.useContext)(ACLActionParamsContext);
    const whitelist = [].concat((null == params ? void 0 : params.whitelist) || []).concat((null == params ? void 0 : params.fields) || []).concat((null == params ? void 0 : params.appends) || []);
    return {
        whitelist,
        schemaInWhitelist (fieldSchema, isSkip) {
            if (isSkip) return true;
            if (0 === whitelist.length) return true;
            if (!fieldSchema) return true;
            if (!fieldSchema['x-collection-field']) return true;
            const [key1, key2] = fieldSchema['x-collection-field'].split('.');
            return null == whitelist ? void 0 : whitelist.includes(key2 || key1);
        }
    };
};
const ACLCollectionFieldProvider = (props)=>{
    const fieldSchema = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.useFieldSchema)();
    const field = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.useField)();
    const { allowAll } = useACLRoleContext();
    const { whitelist } = useACLFieldWhitelist();
    const [name] = fieldSchema.name.split('.');
    const allowed = !!fieldSchema['x-acl-ignore'] || !(whitelist.length > 0) || whitelist.includes(name);
    (0, __WEBPACK_EXTERNAL_MODULE_react__.useEffect)(()=>{
        if (!allowed) {
            field.required = false;
            field.display = 'hidden';
        }
    }, [
        allowed
    ]);
    if (allowAll) return /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.Fragment, {
        children: props.children
    });
    if (!fieldSchema['x-collection-field']) return /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.Fragment, {
        children: props.children
    });
    if (!allowed) return null;
    return /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.Fragment, {
        children: props.children
    });
};
const ACLMenuItemProvider = (props)=>{
    const { allowAll, allowMenuItemIds = [], snippets } = useACLRoleContext();
    const fieldSchema = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.useFieldSchema)();
    if (allowAll || snippets.includes('ui.*')) return /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.Fragment, {
        children: props.children
    });
    if (!fieldSchema['x-uid']) return /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.Fragment, {
        children: props.children
    });
    if (allowMenuItemIds.includes(fieldSchema['x-uid'])) return /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.Fragment, {
        children: props.children
    });
    return null;
};
export { ACLActionParamsContext, ACLActionProvider, ACLCollectionFieldProvider, ACLCollectionProvider, ACLContext, ACLMenuItemProvider, ACLProvider, ACLRolesCheckProvider, useACLActionParamsContext, useACLContext, useACLFieldWhitelist, useACLRoleContext, useACLRolesCheck, useRecordPkValue, useRoleRecheck };
