import { useCallback, useEffect, useState } from 'react';
import { filter, flatten, isNil, map, mergeLeft, pipe, prop, propEq, reject, uniqBy, when } from 'ramda';
import { getEntityUriFromDCRUri, getTasksForEntity, isDCRUri, isTempUri } from '@reltio/mdm-sdk';
import { useSafePromise } from '../../../hooks/useSafePromise';
import { useWorkflowCheckPermission } from './useWorkflowCheckPermission';
import { useMdmEntityUri, useMdmIsEditableMode, useMdmIsWorkflowEnabled, useMdmProfileLastLoadedTime, useMdmTenant, useMdmWorkflowEnvironmentUrl, useMdmWorkflowPath } from '../../../contexts/MdmModuleContext';
import { isRequestedTask } from '../helpers/common';
export var useWorkflowTasks = function (config) {
    var _a = config || {}, processTypes = _a.processTypes, assignee = _a.assignee, showClosedTasks = _a.showClosedTasks;
    var _b = useState(null), tasks = _b[0], setTasks = _b[1];
    var _c = useState(0), total = _c[0], setTotal = _c[1];
    var _d = useState(false), loading = _d[0], setLoading = _d[1];
    var safePromise = useSafePromise();
    var checkWorkflowPermission = useWorkflowCheckPermission();
    var workflowPath = useMdmWorkflowPath();
    var environment = useMdmWorkflowEnvironmentUrl();
    var isWorkflowEnabled = useMdmIsWorkflowEnabled();
    var tenant = useMdmTenant();
    var entityUri = useMdmEntityUri();
    var isEditableMode = useMdmIsEditableMode();
    var entityLastLoadedTime = useMdmProfileLastLoadedTime();
    var canViewTasks = checkWorkflowPermission('VIEW_TASKS');
    var enabled = !!(workflowPath && environment) && isWorkflowEnabled && canViewTasks;
    var loadTasks = useCallback(function () {
        setLoading(true);
        var parsedProcessTypes = !Array.isArray(processTypes) || processTypes.includes('*') ? null : processTypes;
        var requests = (parsedProcessTypes || [null]).map(function (processType) {
            return getTasksForEntity({
                entityUri: isDCRUri(entityUri) ? getEntityUriFromDCRUri(entityUri) : entityUri,
                workflowPath: workflowPath,
                environment: environment,
                tenant: tenant,
                filter: { assignee: assignee, processType: processType },
                includeClosed: !!showClosedTasks
            });
        });
        safePromise(Promise.all(requests))
            .then(function (responses) {
            var tasks = pipe(map(prop('data')), reject(isNil), flatten, uniqBy(prop('taskId')), filter(isRequestedTask(parsedProcessTypes, assignee)))(responses);
            setTasks(tasks);
            setTotal(tasks.length);
        })
            .catch(function (error) {
            console.warn('Workflow error', error);
        })
            .finally(function () {
            setLoading(false);
        });
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [
        entityUri,
        environment,
        safePromise,
        tenant,
        workflowPath,
        assignee,
        showClosedTasks,
        processTypes,
        entityLastLoadedTime
    ]);
    useEffect(function () {
        if (entityUri && enabled && !isTempUri(entityUri)) {
            loadTasks();
        }
        else {
            setTasks(null);
            setTotal(0);
        }
    }, [enabled, entityUri, loadTasks, isEditableMode]);
    var updateTaskState = useCallback(function (taskId, payload) {
        setTasks(map(when(propEq('taskId', taskId), mergeLeft(payload))));
    }, []);
    return {
        tasks: tasks,
        total: total,
        loading: loading,
        updateTaskState: updateTaskState,
        loadTasks: loadTasks
    };
};
