fix(ui): rerender shared toggle buttons properly
[e-mobility-charging-stations-simulator.git] / ui / web / src / views / ChargingStationsView.vue
index 5e385955fb060abef6d59dfbffb1d85a94f19703..c49449f636080a922362f3618d4334ff3354bada 100644 (file)
 <template>
-  <Container id="charging-stations">
-    <Button id="simulator-button" @click="startSimulator()">Start Simulator</Button>
-    <Button id="simulator-button" @click="stopSimulator()">Stop Simulator</Button>
-    <Container id="inputs-container">
-      <input
-        id="idtag-field"
-        v-model="state.idTag"
-        type="text"
-        name="idtag-field"
-        placeholder="RFID tag"
+  <Container id="charging-stations-container">
+    <Container
+      v-show="Array.isArray(uiServerConfigurations) && uiServerConfigurations.length > 1"
+      id="ui-server-container"
+    >
+      <select
+        id="ui-server-selector"
+        v-model="state.uiServerIndex"
+        @change="
+          () => {
+            if (
+              getFromLocalStorage<number>('uiServerConfigurationIndex', 0) !== state.uiServerIndex
+            ) {
+              app?.appContext.config.globalProperties.$uiClient.setConfiguration(
+                app?.appContext.config.globalProperties.$configuration.uiServer[state.uiServerIndex]
+              )
+              initializeWSEventListeners()
+              app?.appContext.config.globalProperties.$uiClient.registerWSEventListener(
+                'open',
+                () => {
+                  setToLocalStorage<number>('uiServerConfigurationIndex', state.uiServerIndex)
+                  $router.currentRoute.value.name !== 'charging-stations' &&
+                    $router.push({ name: 'charging-stations' })
+                },
+                { once: true }
+              )
+              app?.appContext.config.globalProperties.$uiClient.registerWSEventListener(
+                'error',
+                () => {
+                  state.uiServerIndex = getFromLocalStorage<number>('uiServerConfigurationIndex', 0)
+                  app?.appContext.config.globalProperties.$uiClient.setConfiguration(
+                    app?.appContext.config.globalProperties.$configuration.uiServer[
+                      getFromLocalStorage<number>('uiServerConfigurationIndex', 0)
+                    ]
+                  )
+                  initializeWSEventListeners()
+                },
+                { once: true }
+              )
+            }
+          }
+        "
+      >
+        <option
+          v-for="uiServerConfiguration in uiServerConfigurations"
+          :value="uiServerConfiguration.index"
+        >
+          {{ uiServerConfiguration.configuration.name ?? uiServerConfiguration.configuration.host }}
+        </option>
+      </select>
+    </Container>
+    <Container id="buttons-container">
+      <Button @click="startSimulator()">Start Simulator</Button>
+      <Button @click="stopSimulator()">Stop Simulator</Button>
+      <ToggleButton
+        :id="'add-charging-stations'"
+        :key="state.renderAddChargingStations"
+        :shared="true"
+        :on="
+          () => {
+            $router.push({ name: 'add-charging-stations' })
+          }
+        "
+        :off="
+          () => {
+            $router.push({ name: 'charging-stations' })
+          }
+        "
+        @clicked="
+          () => {
+            state.renderChargingStations = randomUUID()
+          }
+        "
+      >
+        Add Charging Stations
+      </ToggleButton>
+      <ReloadButton
+        id="reload-button"
+        :loading="state.loading"
+        @click="loadChargingStations(() => (state.renderChargingStations = randomUUID()))"
       />
-      <ReloadButton id="reload-button" :loading="state.isLoading" @click="load()" />
     </Container>
-    <CSTable :charging-stations="state.chargingStations" :id-tag="state.idTag" />
+    <CSTable
+      v-show="
+        Array.isArray(app?.appContext.config.globalProperties.$chargingStations) &&
+        app.appContext.config.globalProperties.$chargingStations.length > 0
+      "
+      :key="state.renderChargingStations"
+      :charging-stations="app?.appContext.config.globalProperties.$chargingStations"
+      @need-refresh="
+        () => {
+          state.renderAddChargingStations = randomUUID()
+          state.renderChargingStations = randomUUID()
+        }
+      "
+    />
   </Container>
 </template>
 
 <script setup lang="ts">
-import { onMounted, reactive } from 'vue'
+import { getCurrentInstance, onMounted, ref } from 'vue'
+import { useToast } from 'vue-toast-notification'
 import CSTable from '@/components/charging-stations/CSTable.vue'
-import type { ChargingStationData } from '@/types'
+import type { ResponsePayload, UIServerConfigurationSection } from '@/types'
 import Container from '@/components/Container.vue'
 import ReloadButton from '@/components/buttons/ReloadButton.vue'
-import { UIClient } from '@/composables/UIClient'
+import Button from '@/components/buttons/Button.vue'
+import {
+  getFromLocalStorage,
+  getLocalStorage,
+  randomUUID,
+  removeFromLocalStorage,
+  setToLocalStorage
+} from '@/composables'
+import ToggleButton from '@/components/buttons/ToggleButton.vue'
 
-const UIClientInstance = UIClient.getInstance()
+const app = getCurrentInstance()
 
-onMounted(() => {
-  UIClientInstance.registerWSonOpenListener(load)
-})
+const clearToggleButtons = (): void => {
+  for (const key in getLocalStorage()) {
+    if (key.includes('toggle-button')) {
+      removeFromLocalStorage(key)
+    }
+  }
+}
+
+const clearChargingStations = (): void => {
+  clearToggleButtons()
+  app!.appContext.config.globalProperties.$chargingStations = []
+  state.value.renderAddChargingStations = randomUUID()
+  state.value.renderChargingStations = randomUUID()
+}
 
-type State = {
-  isLoading: boolean
-  chargingStations: ChargingStationData[]
-  idTag: string
+const initializeWSEventListeners = () => {
+  app?.appContext.config.globalProperties.$uiClient.registerWSEventListener('open', () => {
+    uiClient
+      .listTemplates()
+      .then((response: ResponsePayload) => {
+        if (app != null) {
+          app.appContext.config.globalProperties.$templates = response.templates
+        }
+      })
+      .catch((error: Error) => {
+        if (app != null) {
+          app.appContext.config.globalProperties.$templates = []
+        }
+        $toast.error('Error at fetching charging station templates')
+        console.error('Error at fetching charging station templates:', error)
+      })
+    loadChargingStations(() => {
+      state.value.renderAddChargingStations = randomUUID()
+      state.value.renderChargingStations = randomUUID()
+    })
+  })
+  app?.appContext.config.globalProperties.$uiClient.registerWSEventListener(
+    'error',
+    clearChargingStations
+  )
+  app?.appContext.config.globalProperties.$uiClient.registerWSEventListener(
+    'close',
+    clearChargingStations
+  )
 }
 
-const state: State = reactive({
-  isLoading: false,
-  chargingStations: [],
-  idTag: ''
+onMounted(() => {
+  initializeWSEventListeners()
+})
+
+const state = ref({
+  renderAddChargingStations: randomUUID(),
+  renderChargingStations: randomUUID(),
+  loading: false,
+  uiServerIndex: getFromLocalStorage<number>('uiServerConfigurationIndex', 0)
 })
 
-async function load(): Promise<void> {
-  if (state.isLoading === true) return
-  state.isLoading = true
-  const listChargingStationsPayload = await UIClientInstance.listChargingStations()
-  state.chargingStations =
-    listChargingStationsPayload.chargingStations as unknown as ChargingStationData[]
-  state.isLoading = false
+const uiClient = app?.appContext.config.globalProperties.$uiClient
+const uiServerConfigurations: { configuration: UIServerConfigurationSection; index: number }[] =
+  app?.appContext.config.globalProperties.$configuration.uiServer.map(
+    (configuration: UIServerConfigurationSection, index: number) => ({
+      configuration,
+      index
+    })
+  )
+
+const $toast = useToast()
+
+const loadChargingStations = (renderCallback?: () => void): void => {
+  if (state.value.loading === false) {
+    state.value.loading = true
+    uiClient
+      .listChargingStations()
+      .then((response: ResponsePayload) => {
+        if (app != null) {
+          app.appContext.config.globalProperties.$chargingStations = response.chargingStations
+        }
+      })
+      .catch((error: Error) => {
+        if (app != null) {
+          app.appContext.config.globalProperties.$chargingStations = []
+        }
+        $toast.error('Error at fetching charging stations')
+        console.error('Error at fetching charging stations:', error)
+      })
+      .finally(() => {
+        if (renderCallback != null) {
+          renderCallback()
+        }
+        state.value.loading = false
+      })
+  }
 }
 
-function startSimulator(): void {
-  UIClientInstance.startSimulator()
+const startSimulator = (): void => {
+  uiClient
+    .startSimulator()
+    .then(() => {
+      $toast.success('Simulator successfully started')
+    })
+    .catch((error: Error) => {
+      $toast.error('Error at starting simulator')
+      console.error('Error at starting simulator:', error)
+    })
 }
-function stopSimulator(): void {
-  UIClientInstance.stopSimulator()
+const stopSimulator = (): void => {
+  uiClient
+    .stopSimulator()
+    .then(() => {
+      if (app != null) {
+        app.appContext.config.globalProperties.$chargingStations = []
+      }
+      $toast.success('Simulator successfully stopped')
+    })
+    .catch((error: Error) => {
+      $toast.error('Error at stopping simulator')
+      console.error('Error at stopping simulator:', error)
+    })
 }
 </script>
 
 <style>
-#charging-stations {
-  height: 100%;
+#charging-stations-container {
+  height: fit-content;
   width: 100%;
-  padding: 30px;
-  background-color: rgb(233, 227, 227);
   display: flex;
   flex-direction: column;
-  gap: 0.5%;
 }
 
-#inputs-container {
+#ui-server-container {
+  display: flex;
+  flex-direction: row;
+}
+
+#ui-server-selector {
+  width: 100%;
+  text-align: center;
+}
+
+#buttons-container {
   display: flex;
-  justify-content: space-between;
+  flex-direction: row;
+}
+
+#action-button {
+  flex: none;
 }
 
 #reload-button {
   flex: auto;
-  padding: 5px 15px;
-  background-color: rgb(25, 118, 210);
-  border-radius: 5px;
   color: white;
-  font-size: 35px;
+  background-color: blue;
+  font-size: 1.5rem;
   font-weight: bold;
+  align-items: center;
+  justify-content: center;
 }
 
 #reload-button:hover {
-  background-color: rgb(10, 113, 195);
+  background-color: rgb(0, 0, 225);
 }
 
 #reload-button:active {
-  background-color: rgb(255, 113, 195);
-}
-
-#simulator-button {
-  flex: auto;
+  background-color: red;
 }
 
-#idtag-field {
-  flex: auto;
+#action {
+  color: white;
+  background-color: black;
+  padding: 1%;
 }
 </style>