1import api from '@/store/api';
2import i18n from '@/i18n';
3
4const PowerControlStore = {
5  namespaced: true,
6  state: {
7    powerCapValue: null,
8    powerCapUri: '',
9    powerConsumptionValue: null,
10  },
11  getters: {
12    powerCapValue: (state) => state.powerCapValue,
13    powerCapUri: (state) => state.powerCapUri,
14    powerConsumptionValue: (state) => state.powerConsumptionValue,
15  },
16  mutations: {
17    setPowerCapValue: (state, powerCapValue) =>
18      (state.powerCapValue = powerCapValue),
19    setPowerCapUri: (state, powerCapUri) => (state.powerCapUri = powerCapUri),
20    setPowerConsumptionValue: (state, powerConsumptionValue) =>
21      (state.powerConsumptionValue = powerConsumptionValue),
22  },
23  actions: {
24    setPowerCapUpdatedValue({ commit }, value) {
25      commit('setPowerCapValue', value);
26    },
27    async getChassisCollection() {
28      return await api
29        .get('/redfish/v1/')
30        .then((response) => api.get(response.data.Chassis['@odata.id']))
31        .then(({ data: { Members } }) =>
32          Members.map((member) => member['@odata.id'])
33        )
34        .catch((error) => console.log(error));
35    },
36    async getPowerControl({ dispatch, commit }) {
37      const collection = await dispatch('getChassisCollection');
38      if (!collection || collection.length === 0) return;
39      return await api
40        .get(`${collection[0]}`)
41        .then((response) => api.get(response.data.Power['@odata.id']))
42        .then((response) => {
43          const powerControl = response.data.PowerControl;
44          if (!powerControl || powerControl.length === 0) return;
45          const powerCapUri = response.data['@odata.id'];
46          const powerCap = powerControl[0].PowerLimit.LimitInWatts;
47          // If system is powered off, power consumption does not exist in the PowerControl
48          const powerConsumption = powerControl[0].PowerConsumedWatts || null;
49          commit('setPowerCapUri', powerCapUri);
50          commit('setPowerCapValue', powerCap);
51          commit('setPowerConsumptionValue', powerConsumption);
52        })
53        .catch((error) => {
54          console.log('Power control', error);
55        });
56    },
57    async setPowerControl({ state }, powerCapValue) {
58      const data = {
59        PowerControl: [{ PowerLimit: { LimitInWatts: powerCapValue } }],
60      };
61      return await api
62        .patch(state.powerCapUri, data)
63        .then(() =>
64          i18n.t('pageServerPowerOperations.toast.successSaveSettings')
65        )
66        .catch((error) => {
67          console.log(error);
68          throw new Error(
69            i18n.t('pageServerPowerOperations.toast.errorSaveSettings')
70          );
71        });
72    },
73  },
74};
75
76export default PowerControlStore;
77