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(() => i18n.tc('pageEventLogs.toast.successDelete', data.length))
88        .catch((error) => {
89          console.log(error);
90          throw new Error(
91            i18n.tc('pageEventLogs.toast.errorDelete', data.length),
92          );
93        });
94    },
95    async deleteEventLogs({ dispatch }, uris = []) {
96      const promises = uris.map((uri) =>
97        api.delete(uri).catch((error) => {
98          console.log(error);
99          return error;
100        }),
101      );
102      return await api
103        .all(promises)
104        .then((response) => {
105          dispatch('getEventLogData');
106          return response;
107        })
108        .then(
109          api.spread((...responses) => {
110            const { successCount, errorCount } = getResponseCount(responses);
111            const toastMessages = [];
112
113            if (successCount) {
114              const message = i18n.tc(
115                'pageEventLogs.toast.successDelete',
116                successCount,
117              );
118              toastMessages.push({ type: 'success', message });
119            }
120
121            if (errorCount) {
122              const message = i18n.tc(
123                'pageEventLogs.toast.errorDelete',
124                errorCount,
125              );
126              toastMessages.push({ type: 'error', message });
127            }
128
129            return toastMessages;
130          }),
131        );
132    },
133    async resolveEventLogs({ dispatch }, logs) {
134      const promises = logs.map((log) =>
135        api.patch(log.uri, { Resolved: true }).catch((error) => {
136          console.log(error);
137          return error;
138        }),
139      );
140      return await api
141        .all(promises)
142        .then((response) => {
143          dispatch('getEventLogData');
144          return response;
145        })
146        .then(
147          api.spread((...responses) => {
148            const { successCount, errorCount } = getResponseCount(responses);
149            const toastMessages = [];
150            if (successCount) {
151              const message = i18n.tc(
152                'pageEventLogs.toast.successResolveLogs',
153                successCount,
154              );
155              toastMessages.push({ type: 'success', message });
156            }
157            if (errorCount) {
158              const message = i18n.tc(
159                'pageEventLogs.toast.errorResolveLogs',
160                errorCount,
161              );
162              toastMessages.push({ type: 'error', message });
163            }
164            return toastMessages;
165          }),
166        );
167    },
168    async unresolveEventLogs({ dispatch }, logs) {
169      const promises = logs.map((log) =>
170        api.patch(log.uri, { Resolved: false }).catch((error) => {
171          console.log(error);
172          return error;
173        }),
174      );
175      return await api
176        .all(promises)
177        .then((response) => {
178          dispatch('getEventLogData');
179          return response;
180        })
181        .then(
182          api.spread((...responses) => {
183            const { successCount, errorCount } = getResponseCount(responses);
184            const toastMessages = [];
185            if (successCount) {
186              const message = i18n.tc(
187                'pageEventLogs.toast.successUnresolveLogs',
188                successCount,
189              );
190              toastMessages.push({ type: 'success', message });
191            }
192            if (errorCount) {
193              const message = i18n.tc(
194                'pageEventLogs.toast.errorUnresolveLogs',
195                errorCount,
196              );
197              toastMessages.push({ type: 'error', message });
198            }
199            return toastMessages;
200          }),
201        );
202    },
203    // Single log entry
204    async updateEventLogStatus({ dispatch }, log) {
205      const updatedEventLogStatus = log.status;
206      return await api
207        .patch(log.uri, { Resolved: updatedEventLogStatus })
208        .then(() => {
209          dispatch('getEventLogData');
210        })
211        .then(() => {
212          if (log.status) {
213            return i18n.tc('pageEventLogs.toast.successResolveLogs', 1);
214          } else {
215            return i18n.tc('pageEventLogs.toast.successUnresolveLogs', 1);
216          }
217        })
218        .catch((error) => {
219          console.log(error);
220          throw new Error(i18n.t('pageEventLogs.toast.errorLogStatusUpdate'));
221        });
222    },
223    async downloadEntry(_, uri) {
224      return await api
225        .get(uri)
226        .then((response) => {
227          const blob = new Blob([response.data], {
228            type: response.headers['content-type'],
229          });
230          return blob;
231        })
232        .catch((error) => {
233          console.log(error);
234          throw new Error(
235            i18n.t('pageEventLogs.toast.errorDownloadEventEntry'),
236          );
237        });
238    },
239  },
240};
241
242export default EventLogStore;
243