<!-- This is useful in an environment where the download doesn't work. -->
<template>
  <QuickNav selected="" />
  <TopMessage />

  <!-- CONTENT -->
  <section id="Content" class="p-6 pb-24 max-w-3xl mx-auto">
    <!-- Back Button -->
    <div class="relative px-7">
      <h1
        class="text-lg text-center font-light px-2 py-1 absolute -left-2 -top-1"
        @click="$router.back()"
      >
        <font-awesome icon="chevron-left" class="mr-2" />
      </h1>
    </div>

    <!-- Heading -->
    <h1 id="ViewHeading" class="text-4xl text-center font-light mb-6">Logs</h1>

    <!-- Error Message -->
    <div
      v-if="error"
      class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-4"
    >
      <span>{{ error }}</span>
    </div>

    <!-- Log Content -->
    <div v-if="loading" class="text-center">
      <font-awesome icon="spinner" class="fa-spin text-slate-400" />
      Loading logs...
    </div>
    <div v-else-if="!logs.length" class="text-center text-slate-500">
      No logs found.
    </div>
    <div v-else>
      <div v-for="(log, index) in logs" :key="index" class="mb-2">
        <pre
          class="bg-slate-100 p-4 rounded-md overflow-x-auto whitespace-pre-wrap"
          >{{ log.date }} {{ log.message }}</pre
        >
      </div>
    </div>
    <div class="text-slate-500">
      <h2 class="text-lg font-bold mb-2">Memory Logs</h2>
      <pre
        class="bg-slate-100 p-4 rounded-md overflow-x-auto whitespace-pre-wrap"
        >{{ memoryLogs.join("\n") }}</pre
      >
    </div>
  </section>
</template>

<script lang="ts">
import { Component, Vue } from "vue-facing-decorator";
import { Router } from "vue-router";

import QuickNav from "../components/QuickNav.vue";
import TopMessage from "../components/TopMessage.vue";
import { db } from "../db/index";
import { Log } from "../db/tables/logs";
import { logger } from "../utils/logger";
import { PlatformServiceFactory } from "../services/PlatformServiceFactory";
import { USE_DEXIE_DB } from "../constants/app";
import * as databaseUtil from "../db/databaseUtil";

@Component({
  components: {
    QuickNav,
    TopMessage,
  },
})
export default class LogView extends Vue {
  $router!: Router;

  loading = true;
  logs: Log[] = [];
  error: string | null = null;
  memoryLogs: string[] = [];

  async mounted() {
    await this.loadLogs();
  }

  async loadLogs() {
    try {
      this.error = null; // Clear any previous errors
      this.memoryLogs = databaseUtil.memoryLogs;

      let allLogs: Log[] = [];
      const platformService = PlatformServiceFactory.getInstance();
      const queryResult = await platformService.dbQuery(
        "SELECT * FROM logs ORDER BY date DESC",
      );
      this.logs = databaseUtil.mapQueryResultToValues(
        queryResult,
      ) as unknown as Log[];
      if (USE_DEXIE_DB) {
        await db.open();
        allLogs = await db.logs.toArray();
        // Sort by date in reverse chronological order
        this.logs = allLogs.sort((a, b) => {
          const dateA = new Date(a.date);
          const dateB = new Date(b.date);
          return dateB.getTime() - dateA.getTime();
        });
      }
    } catch (error) {
      logger.error("Error loading logs:", error);
      this.error =
        error instanceof Error
          ? error.message
          : `An unknown error occurred while loading logs: ${String(error)}`;
    } finally {
      this.loading = false;
    }
  }
}
</script>
