1import api, { getResponseCount } from '@/store/api';
2import i18n from '@/i18n';
3
4const getHealthStatus = (events, loadedEvents) => {
5  let status = loadedEvents ? 'OK' : '';
6  for (const event of events) {
7    if (event.filterByStatus === 'Unresolved') {
8      if (event.severity === 'Warning') {
9        status = 'Warning';
10      }
11      if (event.severity === 'Critical') {
12        status = 'Critical';
13        break;
14      }
15    }
16  }
17  return status;
18};
19
20// TODO: High priority events should also check if Log
21// is resolved when the property is available in Redfish
22const getHighPriorityEvents = (events) =>
23  events.filter(({ severity }) => severity === 'Critical');
24
25const EventLogStore = {
26  namespaced: true,
27  state: {
28    allEvents: [],
29    loadedEvents: false,
30  },
31  getters: {
32    allEvents: (state) => state.allEvents,
33    highPriorityEvents: (state) => getHighPriorityEvents(state.allEvents),
34    healthStatus: (state) =>
35      getHealthStatus(state.allEvents, state.loadedEvents),
36  },
37  mutations: {
38    setAllEvents: (state, allEvents) => (
39      (state.allEvents = allEvents), (state.loadedEvents = true)
40    ),
41  },
42  actions: {
43    async getEventLogData({ commit }) {
44      return await api
45        .get('/redfish/v1/Systems/system/LogServices/EventLog/Entries')
46        .then(({ data: { Members = [] } = {} }) => {
47          const eventLogs = Members.map((log) => {
48            const {
49              Id,
50              Severity,
51              Created,
52              EntryType,
53              Message,
54              Name,
55              Modified,
56              Resolved,
57              AdditionalDataURI,
58            } = log;
59            return {
60              id: Id,
61              severity: Severity,
62              date: new Date(Created),
63              type: EntryType,
64              description: Message,
65              name: Name,
66              modifiedDate: new Date(Modified),
67              uri: log['@odata.id'],
68              filterByStatus: Resolved ? 'Resolved' : 'Unresolved',
69              status: Resolved, //true or false
70              additionalDataUri: AdditionalDataURI,
71            };
72          });
73          commit('setAllEvents', eventLogs);
74        })
75        .catch((error) => {
76          console.log('Event Log Data:', error);
77        });
78    },
79    async deleteAllEventLogs({ dispatch }, data) {
80      return await api
81        .post(
82          '/redfish/v1/Systems/system/LogServices/EventLog/Actions/LogService.ClearLog',
83        )
84        .then(() => dispatch('getEventLogData'))
85        .then(() => i18n.tc('pageEventLogs.toast.successDelete', data.length))
86        .catch((error) => {
87          console.log(error);
88          throw new Error(
89            i18n.tc('pageEventLogs.toast.errorDelete', data.length),
90          );
91        });
92    },
93    async deleteEventLogs({ dispatch }, uris = []) {
94      const promises = uris.map((uri) =>
95        api.delete(uri).catch((error) => {
96          console.log(error);
97          return error;
98        }),
99      );
100      return await api
101        .all(promises)
102        .then((response) => {
103          dispatch('getEventLogData');
104          return response;
105        })
106        .then(
107          api.spread((...responses) => {
108            const { successCount, errorCount } = getResponseCount(responses);
109            const toastMessages = [];
110
111            if (successCount) {
112              const message = i18n.tc(
113                'pageEventLogs.toast.successDelete',
114                successCount,
115              );
116              toastMessages.push({ type: 'success', message });
117            }
118
119            if (errorCount) {
120              const message = i18n.tc(
121                'pageEventLogs.toast.errorDelete',
122                errorCount,
123              );
124              toastMessages.push({ type: 'error', message });
125            }
126
127            return toastMessages;
128          }),
129        );
130    },
131    async resolveEventLogs({ dispatch }, logs) {
132      const promises = logs.map((log) =>
133        api.patch(log.uri, { Resolved: true }).catch((error) => {
134          console.log(error);
135          return error;
136        }),
137      );
138      return await api
139        .all(promises)
140        .then((response) => {
141          dispatch('getEventLogData');
142          return response;
143        })
144        .then(
145          api.spread((...responses) => {
146            const { successCount, errorCount } = getResponseCount(responses);
147            const toastMessages = [];
148            if (successCount) {
149              const message = i18n.tc(
150                'pageEventLogs.toast.successResolveLogs',
151                successCount,
152              );
153              toastMessages.push({ type: 'success', message });
154            }
155            if (errorCount) {
156              const message = i18n.tc(
157                'pageEventLogs.toast.errorResolveLogs',
158                errorCount,
159              );
160              toastMessages.push({ type: 'error', message });
161            }
162            return toastMessages;
163          }),
164        );
165    },
166    async unresolveEventLogs({ dispatch }, logs) {
167      const promises = logs.map((log) =>
168        api.patch(log.uri, { Resolved: false }).catch((error) => {
169          console.log(error);
170          return error;
171        }),
172      );
173      return await api
174        .all(promises)
175        .then((response) => {
176          dispatch('getEventLogData');
177          return response;
178        })
179        .then(
180          api.spread((...responses) => {
181            const { successCount, errorCount } = getResponseCount(responses);
182            const toastMessages = [];
183            if (successCount) {
184              const message = i18n.tc(
185                'pageEventLogs.toast.successUnresolveLogs',
186                successCount,
187              );
188              toastMessages.push({ type: 'success', message });
189            }
190            if (errorCount) {
191              const message = i18n.tc(
192                'pageEventLogs.toast.errorUnresolveLogs',
193                errorCount,
194              );
195              toastMessages.push({ type: 'error', message });
196            }
197            return toastMessages;
198          }),
199        );
200    },
201    // Single log entry
202    async updateEventLogStatus({ dispatch }, log) {
203      const updatedEventLogStatus = log.status;
204      return await api
205        .patch(log.uri, { Resolved: updatedEventLogStatus })
206        .then(() => {
207          dispatch('getEventLogData');
208        })
209        .then(() => {
210          if (log.status) {
211            return i18n.tc('pageEventLogs.toast.successResolveLogs', 1);
212          } else {
213            return i18n.tc('pageEventLogs.toast.successUnresolveLogs', 1);
214          }
215        })
216        .catch((error) => {
217          console.log(error);
218          throw new Error(i18n.t('pageEventLogs.toast.errorLogStatusUpdate'));
219        });
220    },
221  },
222};
223
224export default EventLogStore;
225