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(
46          `${await this.dispatch('global/getSystemPath')}/LogServices/EventLog/Entries`,
47        )
48        .then(({ data: { Members = [] } = {} }) => {
49          const eventLogs = Members.map((log) => {
50            const {
51              Id,
52              Severity,
53              Created,
54              EntryType,
55              Message,
56              Name,
57              Modified,
58              Resolved,
59              AdditionalDataURI,
60            } = log;
61            return {
62              id: Id,
63              severity: Severity,
64              date: new Date(Created),
65              type: EntryType,
66              description: Message,
67              name: Name,
68              modifiedDate: new Date(Modified),
69              uri: log['@odata.id'],
70              filterByStatus: Resolved ? 'Resolved' : 'Unresolved',
71              status: Resolved, //true or false
72              additionalDataUri: AdditionalDataURI,
73            };
74          });
75          commit('setAllEvents', eventLogs);
76        })
77        .catch((error) => {
78          console.log('Event Log Data:', error);
79        });
80    },
81    async deleteAllEventLogs({ dispatch }, data) {
82      return await api
83        .post(
84          `${await this.dispatch('global/getSystemPath')}/LogServices/EventLog/Actions/LogService.ClearLog`,
85        )
86        .then(() => dispatch('getEventLogData'))
87        .then(() =>
88          i18n.global.t('pageEventLogs.toast.successDelete', data.length),
89        )
90        .catch((error) => {
91          console.log(error);
92          throw new Error(
93            i18n.global.t('pageEventLogs.toast.errorDelete', data.length),
94          );
95        });
96    },
97    async deleteEventLogs({ dispatch }, uris = []) {
98      const promises = uris.map((uri) =>
99        api.delete(uri).catch((error) => {
100          console.log(error);
101          return error;
102        }),
103      );
104      return await api
105        .all(promises)
106        .then((response) => {
107          dispatch('getEventLogData');
108          return response;
109        })
110        .then(
111          api.spread((...responses) => {
112            const { successCount, errorCount } = getResponseCount(responses);
113            const toastMessages = [];
114
115            if (successCount) {
116              const message = i18n.global.t(
117                'pageEventLogs.toast.successDelete',
118                successCount,
119              );
120              toastMessages.push({ type: 'success', message });
121            }
122
123            if (errorCount) {
124              const message = i18n.global.t(
125                'pageEventLogs.toast.errorDelete',
126                errorCount,
127              );
128              toastMessages.push({ type: 'error', message });
129            }
130
131            return toastMessages;
132          }),
133        );
134    },
135    async resolveEventLogs({ dispatch }, logs) {
136      const promises = logs.map((log) =>
137        api.patch(log.uri, { Resolved: true }).catch((error) => {
138          console.log(error);
139          return error;
140        }),
141      );
142      return await api
143        .all(promises)
144        .then((response) => {
145          dispatch('getEventLogData');
146          return response;
147        })
148        .then(
149          api.spread((...responses) => {
150            const { successCount, errorCount } = getResponseCount(responses);
151            const toastMessages = [];
152            if (successCount) {
153              const message = i18n.global.t(
154                'pageEventLogs.toast.successResolveLogs',
155                successCount,
156              );
157              toastMessages.push({ type: 'success', message });
158            }
159            if (errorCount) {
160              const message = i18n.global.t(
161                'pageEventLogs.toast.errorResolveLogs',
162                errorCount,
163              );
164              toastMessages.push({ type: 'error', message });
165            }
166            return toastMessages;
167          }),
168        );
169    },
170    async unresolveEventLogs({ dispatch }, logs) {
171      const promises = logs.map((log) =>
172        api.patch(log.uri, { Resolved: false }).catch((error) => {
173          console.log(error);
174          return error;
175        }),
176      );
177      return await api
178        .all(promises)
179        .then((response) => {
180          dispatch('getEventLogData');
181          return response;
182        })
183        .then(
184          api.spread((...responses) => {
185            const { successCount, errorCount } = getResponseCount(responses);
186            const toastMessages = [];
187            if (successCount) {
188              const message = i18n.global.t(
189                'pageEventLogs.toast.successUnresolveLogs',
190                successCount,
191              );
192              toastMessages.push({ type: 'success', message });
193            }
194            if (errorCount) {
195              const message = i18n.global.t(
196                'pageEventLogs.toast.errorUnresolveLogs',
197                errorCount,
198              );
199              toastMessages.push({ type: 'error', message });
200            }
201            return toastMessages;
202          }),
203        );
204    },
205    // Single log entry
206    async updateEventLogStatus({ dispatch }, log) {
207      const updatedEventLogStatus = log.status;
208      return await api
209        .patch(log.uri, { Resolved: updatedEventLogStatus })
210        .then(() => {
211          dispatch('getEventLogData');
212        })
213        .then(() => {
214          if (log.status) {
215            return i18n.global.t('pageEventLogs.toast.successResolveLogs', 1);
216          } else {
217            return i18n.global.t('pageEventLogs.toast.successUnresolveLogs', 1);
218          }
219        })
220        .catch((error) => {
221          console.log(error);
222          throw new Error(
223            i18n.global.t('pageEventLogs.toast.errorLogStatusUpdate'),
224          );
225        });
226    },
227    async downloadEntry(_, uri) {
228      return await api
229        .get(uri, {
230          headers: {
231            Accept: 'application/octet-stream',
232          },
233        })
234        .then((response) => {
235          const blob = new Blob([response.data], {
236            type: response.headers['content-type'],
237          });
238          return blob;
239        })
240        .catch((error) => {
241          console.log(error);
242          throw new Error(
243            i18n.global.t('pageEventLogs.toast.errorDownloadEventEntry'),
244          );
245        });
246    },
247  },
248};
249
250export default EventLogStore;
251