/**
 * 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 { createSlice } from '@reduxjs/toolkit';
import { useInjectReducer } from 'utils/@reduxjs/injectReducer';
import {
  getDepartment,
  getDepartments,
} from './thunks';
import { DepartmentState } from './types';

export const initialState: DepartmentState = {
  departments: [],
  editingId: '',
  departmentListLoading: false,
  departmentDetailLoading: false,
};

const slice = createSlice({
  name: 'department',
  initialState,
  reducers: {
  },
  extraReducers: builder => {
    // getDepartments
    builder.addCase(getDepartments.pending, state => {
      state.departmentListLoading = true;
    });
    builder.addCase(getDepartments.fulfilled, (state, action) => {
      state.departmentListLoading = false;
      state.departments = action.payload.map(v => ({ ...v, isFolder: v.level>1?true:false }));
    });
    builder.addCase(getDepartments.rejected, state => {
      state.departmentListLoading = false;
    });

    builder.addCase(getDepartment.pending, state => {
      state.departmentDetailLoading = true;
    });
    builder.addCase(getDepartment.fulfilled, (state, action) => {
      state.departmentDetailLoading = false;
      state.departments = state.departments.map(s =>
        s.id === action.payload.id
          ? { ...action.payload, isFolder: action.payload.level>1?true:false }
          : s,
      );
      state.editingId = action.payload.id;
    });
    builder.addCase(getDepartment.rejected, state => {
      state.departmentDetailLoading = false;
    });

  },
});

export const { actions: departmentActions, reducer } = slice;

export const useDepartmentSlice = () => {
  useInjectReducer({ key: slice.name, reducer: slice.reducer });
  return { actions: slice.actions };
};
