<template>
<v-dialog
  v-model="dialog"
  max-width="500"
  scrollable
  style="z-index:2020;"
>
  <template v-slot:activator="{ on, attrs }">
	<small class="ml-3">
      <a v-on="on">
        <span class="d-none d-sm-inline">Get help </span>
        <v-icon small>mdi-account-question</v-icon>
      </a>
	</small>
  </template>

  <v-card>
    <v-window v-model="page">
      <v-window-item value="support">
        <v-card-title class="headline">
          Dougal user support
        </v-card-title>

        <v-card-text>
          <p>You can get help or report a problem by sending an email to <a :href="`mailto:${email}`">{{email}}</a>. Please include as much information as possible about your problem or question—screenshots are often a good idea, and data files may also be attached.</p>

          <p>When you write to the above address a ticket will be automatically created in the project's issue tracking system.</p>

          <v-alert dense type="info" border="left" outlined>
            <div class="text-body-2">
            You are using Dougal version:
            <ul>
              <li><code>{{clientVersion}}</code> (client)</li>
              <li><code>{{serverVersion}}</code> (server)</li>
            </ul>
            </div>
          </v-alert>

        </v-card-text>
      </v-window-item>

      <v-window-item value="changelog">
        <v-card-title class="headline">
          Dougal release notes
        </v-card-title>

        <v-card-text>
          <v-carousel v-model="releaseShown"
            :continuous="false"
            :cycle="false"
            :show-arrows="true"
            :hide-delimiters="true"
          >
            <v-carousel-item v-for="release in releaseHistory">
              <pre>{{release}}</pre>
            </v-carousel-item>
          </v-carousel>
        </v-card-text>


      </v-window-item>
      <v-window-item value="serverinfo">
        <dougal-server-status :status="serverStatus"></dougal-server-status>
      </v-window-item>
    </v-window>

    <v-divider></v-divider>

    <v-card-actions>

      <v-btn
        color="info"
        text
        :href="`mailto:${email}?Subject=Question`"
      >
        <v-icon title="Ask a question">mdi-help-circle</v-icon>
      </v-btn>

      <v-btn
        color="warning darken-1"
        text
        href="mailto:dougal-support@aaltronav.eu?Subject=Bug report"
      >
        <v-icon title="Report a bug">mdi-bug</v-icon>
      </v-btn>

      <!---
      <v-btn
        color="info"
        text
        :href='"/feed/"+feed'
        title="View development log"
      >
        <v-icon>mdi-rss</v-icon>
      </v-btn>
      --->

      <v-btn
        color="info"
        text
        title="View support info"
        :input-value="page == 'support'"
        @click="page = 'support'"
      >
        <v-icon>mdi-account-question</v-icon>
      </v-btn>

      <v-btn v-if="versionHistory"
        color="info"
        text
        title="View release notes"
        :input-value="page == 'changelog'"
        @click="page = 'changelog'"
      >
        <v-icon>mdi-history</v-icon>
      </v-btn>

      <v-btn v-if="serverStatus"
        color="info"
        text
        title="View server status"
        :input-value="page == 'serverinfo'"
        @click="page = 'serverinfo'"
      >
        <v-icon>mdi-server-network</v-icon>
      </v-btn>

      <v-spacer></v-spacer>


      <v-btn
        color="primary darken-1"
        text
        @click="dialog=false"
      >
        <v-icon class="d-lg-none">mdi-close-circle</v-icon>
        <span class="d-none d-lg-inline">Close</span>
      </v-btn>
    </v-card-actions>

  </v-card>

</v-dialog>

</template>

<script>
import { mapActions, mapGetters } from 'vuex';
import DougalServerStatus from './server-status';

export default {
  name: 'DougalHelpDialog',

  components: {
    DougalServerStatus
  },

  data () {
    return {
      dialog: false,
      email: "dougal-support@aaltronav.eu",
      feed: btoa(encodeURIComponent("https://gitlab.com/wgp/dougal/software.atom?feed_token=XSPpvsYEny8YmH75Nz5W")),
      serverStatus: null,
      clientVersion: process.env.DOUGAL_FRONTEND_VERSION ?? "(unknown)",
      serverVersion: null,
      versionHistory: null,
      releaseHistory: [],
      releaseShown: null,
      page: "support",

      lastUpdate: 0,
      updateInterval: 12000,
      refreshTimer: null
    };
  },

  computed: {
    sinceUpdate () {
      return this.lastUpdate
        ? (Date.now() - this.lastUpdate)
        : +Infinity;
    }
  },

  watch: {
    dialog(newVal) {
      if (newVal) {
        this.startAutoRefresh();
      } else {
        this.stopAutoRefresh();
      }
    },
    page(newVal) {
      if (newVal === 'serverinfo' && this.dialog) {
        this.getServerStatus(); // Immediate update when switching to serverinfo
        this.startAutoRefresh();
      } else {
        this.stopAutoRefresh();
      }
    }
  },

  methods: {
    async getServerVersion () {
      if (!this.serverVersion) {
        const version = await this.api(['/version', {}, null, {silent:true}]);
        this.serverVersion = version?.tag ?? "(unknown)";
        if (version) this.lastUpdate = Date.now();
      }
      if (!this.versionHistory) {
        const history = await this.api(['/version/history?count=6', {}, null, {silent:true}]);
        this.releaseHistory = history;
        this.versionHistory = history?.[this.serverVersion.replace(/-.*$/, "")] ?? null;
      }
    },

    async getServerStatus () {
      const status = await this.api(['/diagnostics', {}, null, {silent: true}]);
      if (status) {
        this.serverStatus = status;
        this.lastUpdate = Date.now();
      }
    },

    startAutoRefresh() {
      if (this.refreshTimer) return; // Prevent multiple timers
      this.refreshTimer = setInterval(() => {
        if (this.dialog && this.page === 'serverinfo') {
          this.getServerStatus();
          // Optionally refresh server version if needed
          // this.getServerVersion();
        }
      }, this.updateInterval);
    },

    stopAutoRefresh() {
      if (this.refreshTimer) {
        clearInterval(this.refreshTimer);
        this.refreshTimer = null;
      }
    },

    ...mapActions(["api"])
  },

  async mounted () {
    this.getServerVersion();
    this.getServerStatus();
  },

  beforeDestroy() {
    this.stopAutoRefresh(); // Clean up timer on component destruction
  }

};
</script>
