import * as R from 'ramda';
import {
  ModuleAction,
  ModuleState,
  ModuleItem,
} from './module.interface';
  
  export const initialState: ModuleState = {
    moduleList: [],
    desktopMenus: [],
    isModuleListLoading: true,
    currentMenu: null as unknown as ModuleItem,
    currentModule: ''
  };
  
  export const reducer = (state: ModuleState, action: ModuleAction) => {
    switch (action.type) {
      case "init_module_list": {
        return {
          ...state,
          moduleList: action.payload.data,
          isModuleListLoading: false
        };
      }

      case 'init_menus': {
        console.log('select_module init', action.payload.data)
        return {
          ...state,
          ...action.payload.data,
          isModuleListLoading: false
        }
      }
      
      case 'close_module': {
        const module = action.payload.data;
        const preMenuIndex = R.findIndex(R.propEq('name', module.name), state.desktopMenus as any);
        const currentMenu = preMenuIndex === state.desktopMenus.length - 1 ? state.desktopMenus[preMenuIndex - 1] : state.desktopMenus[preMenuIndex + 1];
        const list = R.filter((item: any) => item.name !== module.name)(state.desktopMenus);
        return {
          ...state,
          desktopMenus: list,
          currentMenu
        }
      }

      case 'lock_module': {
        const module = action.payload.data;
        const list = state.desktopMenus;
        const {moduleId} = module;
        const index = Number(R.findIndex(R.propEq('name', moduleId))(list));
        if(index && list[index]){
          list[index].isLock = true;
        } else {
          list.push({
            ...module,
            isLock: true
          });
        }
        
        return {
          ...state,
          desktopMenus: list
        }
      }

      case 'unlock_module': {
        const module = action.payload.data;
        const list = state.desktopMenus;
        const {moduleId} = module;
        const index = Number(R.findIndex(R.propEq('name', moduleId))(list));
        list[index].isLock = false;
        return {
          ...state,
          desktopMenus: list
        }
      }

      case 'select_module': {
        const {name, moduleId} = action.payload.data;
        const list = state.desktopMenus;
        const index = Number(R.findIndex(R.propEq('name', name))(list));
        if(index < 0 && !list[index]) {
          list.push(action.payload.data);
        }
        return {
          ...state,
          currentMenu: action.payload.data,
          currentModule: moduleId
        }
      }

      case 'update_menu': {
        return {
          ...state,
          currentMenu: action.payload.data
        }
      }
  
      default:
        return state;
    }
  };
  