import {createReducer} from '@reduxjs/toolkit';
import * as Actions from '../actions/release_version_actions';
import * as Constants from '../../constants';

const versionLookup = Constants.RELEASE_TYPES.map(k=> {
  return {
    [k]: ['unavailable']
  };
}).reduce((map, obj) => {
  return {
    ...map,
    ...obj,
  };
});

export const releaseVersionReducer = createReducer({
  AllowDismissDependencies: false,
  DismissNewReleasesAvailable: true,
  InstalledVersion: 'none',
  LocationsLookup: {},
  NewReleasesAvailable: [],
  NewReleasesAvailable2: [],
  Release: 0,
  ReleaseDefault: 0,
  ReleaseUpgradeAvailable: false,
  UpgradeAvailable: false,
  UpgradeData: null,
  UpgradeVersion: null,
  UpgradeDismissed: false,
  Version: -1,
  VersionLookup: versionLookup,
}, {
  [Actions.CLEAR_UI_UPGRADE]: state => {
    return {
      ...state,
      UpgradeAvailable: false,
      UpgradeDismissed: false,
      UpgradeData: null,
      UpgradeVersion: null,
    };
  },
  [Actions.NOTIFY_ACTIVE_RELEASE]: (state, action) => {
    return {
      ...state,
      Release: action.payload.release,
      Version: action.payload.version
    };
  },
  [Actions.setAllowDismissDependencies]: (state, action) => {
    return {
      ...state,
      AllowDismissDependencies: action.payload,
    };
  },
  [Actions.setDismissNewReleasesAvailable]: (state, action) => {
    return {
      ...state,
      DismissNewReleasesAvailable: action.payload,
    };
  },
  [Actions.setDismissUIUpgrade]: (state, action) => {
    return {
      ...state,
      UpgradeDismissed: action.payload,
    };
  },
  [Actions.setInstalledVersion]: (state, action) => {
    return {
      ...state,
      InstalledVersion: action.payload,
    }
  },
  [Actions.setNewReleasesAvailable]: (state, action) => {
    return {
      ...state,
      DismissNewReleasesAvailable: false,
      NewReleasesAvailable: action.payload,
    };
  },
  [Actions.setNewReleasesAvailable2]: (state, action) => {
    return {
      ...state,
      NewReleasesAvailable2: action.payload,
    };
  },
  [Actions.SET_RELEASE_DATA]: (state, action) => {
    return {
      ...state,
      LocationsLookup: action.payload.locations,
      VersionLookup: action.payload.versions,
    };
  },
  [Actions.setReleaseUpgradeAvailable]: (state, action) => {
    return {
      ...state,
      ReleaseUpgradeAvailable: action.payload,
    };
  },
  [Actions.SET_UI_UPGRADE_DATA]: (state, action) => {
    return {
      ...state,
      UpgradeAvailable: true,
      UpgradeData: action.payload.upgrade_data,
      UpgradeVersion: action.payload.version,
      UpgradeDismissed: false,
    };
  }
});
