/**
 * Datart
 *
 * Copyright 2021
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { createSelector } from '@reduxjs/toolkit';
import { RootState } from 'types';
import { listToTree } from 'utils/utils';
import { initialState } from '.';
import { ResourceTypes } from '../../PermissionPage/constants';
import { SelectDepartmentFolderTreeProps, SelectDepartmentTreeProps } from './types';

const selectDomain = (state: RootState) => state.department || initialState;

export const selectDepartments = createSelector(
  [selectDomain],
  state => state.departments,
);

export const selectEditingDepartment = createSelector([selectDomain], state =>
  state.departments
    .find(({ id }) => state.editingId === id),
);

export const makeSelectDepartmentTree = () => 
  createSelector(
    [
      selectDepartments,
      (_, props: SelectDepartmentTreeProps) => props.getIcon,
      (_, props: SelectDepartmentTreeProps) => props.getDisabled,
    ],
    (departments, getIcon, getDisabled) => 
      listToTree(departments, "0", [ResourceTypes.Department], {
        getIcon,
        getDisabled,
      }),
  );

export const makeSelectDepartmentFolderTree = () =>
  createSelector(
    [
      selectDepartments,
      (_, props: SelectDepartmentFolderTreeProps) => props.id,
      (_, props: SelectDepartmentFolderTreeProps) => props.getDisabled,
    ],
    (departments, id, getDisabled) =>
      listToTree(
        departments && departments.filter(v => v.isFolder && v.id !== id),
        null,
        [ResourceTypes.Department],
        { getDisabled },
      ),
  );

export const selectDepartmentsListLoading = createSelector(
  [selectDomain],
  state => state.departmentListLoading,
);
