<template>
  <MainLayout :gap="false">
    <template #dialogs>
      <Dialog ref="fatalErrorDialog" modal title="Error">
        <p>{{ fatalError }}</p>
      </Dialog>

      <InputDialog ref="inputDialog" />
      <a id="fileDownloadLink" :href="downloadFileDownloadUrl" target="_blank"></a>
    </template>
    <template #header>
      <TopBar class="navbar">
        <template #left>
          <span class="title">{{ name }}</span>
        </template>
        <template #right>
          <!-- Scheduler/cron tasks -->
          <Button success :menu="schedulerMenuModel" v-show="usesAddon('scheduler')" @click="onSchedulerMenu">{{ $t('terminal.scheduler') }}</Button>

          <!-- addon actions -->
          <Button success @click="terminalInject('mysql')" v-show="usesAddon('mysql')" :disabled="!connected">MySQL</Button>
          <Button success @click="terminalInject('postgresql')" v-show="usesAddon('postgresql')" :disabled="!connected">Postgres</Button>
          <Button success @click="terminalInject('mongodb')" v-show="usesAddon('mongodb')" :disabled="!connected">MongoDB</Button>
          <Button success @click="terminalInject('redis')" v-show="usesAddon('redis')" :disabled="!connected">Redis</Button>

          <!-- upload/download actions -->
          <Button style="margin-left: 20px;" :disabled="!connected" @click="onUpload" icon="fa-solid fa-upload">{{ $t('terminal.uploadToTmp') }}</Button>
          <Button :disabled="!connected" @click="onDownload" icon="fa-solid fa-download">{{ $t('terminal.downloadAction') }}</Button>

          <Button style="margin-left: 20px;" :title="$t('filemanager.toolbar.restartApp')" secondary :loading="busyRestart" icon="fa-solid fa-arrows-rotate" @click="onRestartApp"/>
          <Button :href="'/frontend/filemanager.html#/home/app/' + id" target="_blank" secondary icon="fa-solid fa-folder" :title="$t('filemanager.title')" />
          <Button :href="'/frontend/logs.html?appId=' + id" target="_blank" secondary icon="fa-solid fa-align-left" :title="$t('logs.title')" />
        </template>
      </TopBar>
    </template>
    <template #body>
      <!-- terminal will be injected here -->
    </template>
    <template #footer>
      <FileUploader
        ref="fileUploader"
        :upload-handler="uploadHandler"
        :tr="$t"
      />
    </template>
  </MainLayout>
</template>

<script>

import superagent from 'superagent';

import { Button, Dialog, FileUploader, InputDialog, MainLayout, TopBar } from 'pankow';

import '@xterm/xterm/css/xterm.css';
import { Terminal } from '@xterm/xterm';
import { AttachAddon } from '@xterm/addon-attach';
import { FitAddon } from '@xterm/addon-fit';

import { create } from '../models/AppModel.js';

const API_ORIGIN = import.meta.env.VITE_API_ORIGIN ? 'https://' + import.meta.env.VITE_API_ORIGIN : window.location.origin;

export default {
  name: 'Terminal',
  components: {
    Button,
    Dialog,
    FileUploader,
    InputDialog,
    MainLayout,
    TopBar
  },
  data() {
    return {
      accessToken: localStorage.token,
      apiOrigin: API_ORIGIN || '',
      appModel: null,
      fatalError: false,
      busyRestart: false,
      connected: false,
      addons: {},
      schedulerTasks: [],
      manifestVersion: '',
      schedulerMenuModel: [],
      id: '',
      name: '',
      socket: null,
      terminal: null,
      downloadFileDownloadUrl: ''
    };
  },
  methods: {
    onFatalError(errorMessage) {
      this.fatalError = errorMessage;
      this.$refs.fatalErrorDialog.open();
    },
    // generic dialog focus handler TODO move to pankow and reuse in filemanger
    onDialogShow(focusElementId) {
      setTimeout(() => document.getElementById(focusElementId).focus(), 0);
    },
    async onDownload() {
      this.downloadFileDownloadUrl = '';

      const downloadFileName = await this.$refs.inputDialog.prompt({
        message: this.$t('terminal.downloadAction'),
        value: '',
        confirmStyle: 'success',
        confirmLabel: this.$t('terminal.download.download'),
        rejectLabel: this.$t('main.dialog.cancel'),
        modal: false
      });

      if (!downloadFileName) return;

      try {
        const result = await superagent.head(`${this.apiOrigin}/api/v1/apps/${this.id}/download`).query({
          file: downloadFileName,
          access_token: this.accessToken
        });
      } catch (error) {
        if (error.status === 404) console.error('The requested file does not exist.');
        else console.error('Failed', error);

        return;
      }

      this.downloadFileDownloadUrl = `${this.apiOrigin}/api/v1/apps/${this.id}/download?file=${encodeURIComponent(downloadFileName)}&access_token=${this.accessToken}`;

      // we have to click the link to make the browser do the download
      // don't know how to prevent the browsers
      this.$nextTick(() => {
        document.getElementById('fileDownloadLink').click();
      });
    },
    onUpload() {
      this.$refs.fileUploader.onUploadFile('/tmp');
    },
    async uploadHandler(targetDir, file, progressHandler) {
      await superagent.post(`${this.apiOrigin}/api/v1/apps/${this.id}/upload`)
        .query({ access_token: this.accessToken, file: `${targetDir}/${file.name}` })
        .attach('file', file)
        .on('progress', progressHandler);
    },
    usesAddon(addon) {
      return !!Object.keys(this.addons).find(function (a) { return a === addon; });
    },
    terminalInject(addon, command) {
      if (!this.socket) return;

      let cmd = '';
      if (addon === 'mysql') {
        if (this.manifestVersion === 1) {
          cmd = 'mysql --user=${MYSQL_USERNAME} --password=${MYSQL_PASSWORD} --host=${MYSQL_HOST} ${MYSQL_DATABASE}';
        } else {
          cmd = 'mysql --user=${CLOUDRON_MYSQL_USERNAME} --password=${CLOUDRON_MYSQL_PASSWORD} --host=${CLOUDRON_MYSQL_HOST} ${CLOUDRON_MYSQL_DATABASE}';
        }
      } else if (addon === 'postgresql') {
      if (this.manifestVersion === 1) {
          cmd = 'PGPASSWORD=${POSTGRESQL_PASSWORD} psql -h ${POSTGRESQL_HOST} -p ${POSTGRESQL_PORT} -U ${POSTGRESQL_USERNAME} -d ${POSTGRESQL_DATABASE}';
        } else {
          cmd = 'PGPASSWORD=${CLOUDRON_POSTGRESQL_PASSWORD} psql -h ${CLOUDRON_POSTGRESQL_HOST} -p ${CLOUDRON_POSTGRESQL_PORT} -U ${CLOUDRON_POSTGRESQL_USERNAME} -d ${CLOUDRON_POSTGRESQL_DATABASE}';
        }
      } else if (addon === 'mongodb') {
        if (this.manifestVersion === 1) {
          cmd = 'mongo -u "${MONGODB_USERNAME}" -p "${MONGODB_PASSWORD}" ${MONGODB_HOST}:${MONGODB_PORT}/${MONGODB_DATABASE}';
        } else {
          cmd = 'mongosh -u "${CLOUDRON_MONGODB_USERNAME}" -p "${CLOUDRON_MONGODB_PASSWORD}" ${CLOUDRON_MONGODB_HOST}:${CLOUDRON_MONGODB_PORT}/${CLOUDRON_MONGODB_DATABASE}';
        }
      } else if (addon === 'redis') {
        if (this.manifestVersion === 1) {
          cmd = 'redis-cli -h "${REDIS_HOST}" -p "${REDIS_PORT}" -a "${REDIS_PASSWORD}"';
        } else {
          cmd = 'redis-cli -h "${CLOUDRON_REDIS_HOST}" -p "${CLOUDRON_REDIS_PORT}" -a "${CLOUDRON_REDIS_PASSWORD}" --no-auth-warning';
        }
      } else if (addon === 'scheduler' && command) {
        cmd = command;
      }

      if (!cmd) return;

      cmd += ' ';

      this.socket.send(cmd);
      this.terminal.focus();
    },
    onSchedulerMenu(event) {
      this.$refs.schedulerMenu.toggle(event);
    },
    async onRestartApp() {
      this.busyRestart = true;
      await this.appModel.restart();
      this.busyRestart = false;
    },
    async connect(retry = false) {
      document.getElementsByClassName('cloudron-layout-body')[0].innerHTML = '';

      let execId;
      try {
        const result = await superagent.post(`${this.apiOrigin}/api/v1/apps/${this.id}/exec`).query({ access_token: this.accessToken }).send({ cmd: [ '/bin/bash' ], tty: true, lang: 'C.UTF-8' });
        execId = result.body.id;
      } catch (error) {
        console.error('Cannot create socket.', error);
        return setTimeout(() => this.connect(true), 1000);
      }

      this.terminal = new Terminal();
      this.terminal.open(document.getElementsByClassName('cloudron-layout-body')[0]);

      if (retry) this.terminal.writeln('Reconnecting...');
      else this.terminal.writeln('Connecting...');

      const fitAddon = new FitAddon();
      this.terminal.loadAddon(fitAddon);
      fitAddon.fit();

      // Let the browser handle paste
      this.terminal.attachCustomKeyEventHandler(function (e) {
        if (e.key === 'V' && (e.ctrlKey || e.metaKey)) return false;
      });

      // websocket cannot use relative urls
      const url = `${this.apiOrigin.replace('https', 'wss')}/api/v1/apps/${this.id}/exec/${execId}/startws?tty=true&rows=${this.terminal.rows}&columns=${this.terminal.cols}&access_token=${this.accessToken}`;
      this.socket = new WebSocket(url);

      this.terminal.loadAddon(new AttachAddon(this.socket));

      this.socket.addEventListener('open', (event) => {
        this.connected = true;
      });

      this.socket.addEventListener('close', (event) => {
        this.connected = false;
        console.log('Socket closed. Reconnecting...');
        return setTimeout(() => this.connect(true), 1000);
      });

      this.socket.addEventListener('error', (error) => {
        this.connected = false;
        console.log('Socket error. Reconnecting...', error);
        return setTimeout(() => this.connect(true), 1000);
      });

      this.terminal.focus();
    }
  },
  async mounted() {
    if (!localStorage.token) {
      console.error('Set localStorage.token');
      return;
    }

    const urlParams = new URLSearchParams(window.location.search);
    const id = urlParams.get('id');

    if (!id) {
      console.error('No app id specified');
      return;
    }

    this.id = id;
    this.name = id;

    this.appModel = create(this.apiOrigin, this.accessToken, this.id);

    try {
      const app = await this.appModel.get();
      this.name = `${app.label || app.fqdn} (${app.manifest.title})`;
      this.addons = app.manifest.addons;
      this.manifestVersion = app.manifest.manifestVersion;

      this.schedulerMenuModel = !app.manifest.addons.scheduler ? [] : Object.keys(app.manifest.addons.scheduler).map((k) => {
        return {
          label: k,
          action: () => this.terminalInject('scheduler', app.manifest.addons.scheduler[k].command)
        };
      });
    } catch (e) {
      console.error(`Failed to get app info for ${this.id}:`, e);
      return this.onFatalError(`Unknown app ${this.id}. Cannot continue.`);
    }

    window.document.title = `Terminal - ${this.name}`;

    window.addEventListener('beforeunload', function (e) {
      e.stopPropagation();
      e.preventDefault();
      return false;
    }, true );

    window.addEventListener('keydown', (event) => {
      if (event.key === 'C' && (event.ctrlKey || event.metaKey)) { // ctrl shift c
        event.preventDefault();

        if (!this.terminal) return;

        // execCommand('copy') would copy any selection from the page, so do this only if terminal has a selection
        if (!this.terminal.getSelection()) return;

        document.execCommand('copy');

        this.terminal.focus();
      }
    });

    this.connect();
  }
};

</script>

<style>

body {
  background-color: black;
  overflow: hidden;
}

.title {
  font-size: 20px;
}

.cloudron-top {
  background-color: black;
  color: white;
  margin-bottom: 0 !important;
  padding: 5px 10px;
}

</style>

<style scoped>

.dialog-header {
  font-weight: 600;
  font-size: 1.25rem;
}

.dialog-single-input {
  display: block;
  width: 100%;
  margin-top: 5px;
  margin-bottom: 1.5rem;
}

.dialog-single-input-submit {
  margin-top: 5px;
}

</style>

