import * as R from 'ramda';
import { createSubscriptionHook } from '@ywfe/hook-subscription';
import {
    DesktopAction,
    DesktopState,
  } from './desktop.interface';
  
  export const initialState: DesktopState = {
    functions: [],
    selected: [],
    menus: []
  };
  
  const reducer = (state: DesktopState, action: DesktopAction) => {
    switch (action.type) {
      case 'init_functions': {
        const functions = action.payload.data;
        const selected = R.pipe(R.map(R.prop('resourceId')))(functions) || [];
        return {
          ...state,
          functions,
          selected: selected as string[]
        }
      }

      case 'toggle_selected': {
        console.log('toggle_selected', action.payload.data)
        return {
          ...state,
          selected: action.payload.data
        }
      }

      case 'init_menus': {
        return {
          ...state,
          menus: action.payload.data
        }
      }

      case 'drag_functions': {
        return {
          ...state,
          functions: action.payload.data
        }
      }

      case 'delete_function': {
        const id = action.payload.data;
        const functions = state.functions.filter((item) => item.resourceId !== id);
        const selected = state.selected.filter((item) => item !== id);
        return {
          ...state,
          functions,
          selected
        }
      }
  
      default:
        return state;
    }
  };
  
  export const useDesktopStore = createSubscriptionHook(
    reducer,
    initialState,
  );