import * as Constants from '../../constants';
import {createReducer} from 'redux-starter-kit';
import {
  displayConfiguration,
  SET_ALLOW_MOUNT,
  setAutoMountProcessed,
  setBusy,
  SET_MOUNT_STATE,
  SET_MOUNTED,
  SET_PROVIDER_STATE
} from '../actions/mount_actions';

const providerState = Constants.PROVIDER_LIST.map(provider=> {
  return {
    [provider]: {
      AutoMount: false,
      AutoRestart: false,
      MountLocation: '',
    }
  }
}).reduce((map, obj) => {
  return {
    ...map,
    ...obj
  }
});

const mountState = Constants.PROVIDER_LIST.map(provider => {
  return {
    [provider]: {
      AllowMount: false,
      DriveLetters: [],
      Mounted: false,
    }
  }
}).reduce((map, obj) => {
  return {
    ...map,
    ...obj
  }
});

export const mountReducer = createReducer({
  AutoMountProcessed: false,
  DisplayConfiguration: null,
  MountsBusy: false,
  MountState: mountState,
  ProviderState: providerState,
}, {
  [displayConfiguration]: (state, action) => {
    return {
      ...state,
      DisplayConfiguration: action.payload
    };
  },
  [setAutoMountProcessed]: (state, action) => {
    return {
      ...state,
      AutoMountProcessed: action.payload
    };
  },
  [SET_ALLOW_MOUNT]: (state, action) => {
    return {
      ...state,
      MountState: {
        ...state.MountState,
        [action.payload.provider]: {
          ...state.MountState[action.payload.provider],
          AllowMount: action.payload.allow,
        }
      }
    };
  },
  [setBusy]: (state, action) => {
    return {
      ...state,
      MountsBusy: action.payload
    };
  },
  [SET_MOUNT_STATE]: (state, action) => {
    return {
      ...state,
      MountState: {
        ...state.MountState,
        [action.payload.provider]: {
          ...state.MountState[action.payload.provider],
          ...action.payload.state
        },
      }
    };
  },
  [SET_MOUNTED]: (state, action) => {
    return {
      ...state,
      MountState: {
        ...state.MountState,
        [action.payload.provider]: {
          ...state.MountState[action.payload.provider],
          Mounted: action.payload.mounted,
        }
      }
    };
  },
  [SET_PROVIDER_STATE]: (state, action) => {
    return {
      ...state,
      ProviderState: {
        ...state.ProviderState,
        [action.payload.provider]: {
          ...state.ProviderState[action.payload.provider],
          ...action.payload.state
        },
      }
    };
  }
});