<script>

import { fetcher, Button } from 'pankow';
import { marked } from 'marked';

import Section from  './Section.vue';

const API_ORIGIN = import.meta.env.VITE_API_ORIGIN ? import.meta.env.VITE_API_ORIGIN : window.location.origin;
const accessToken = localStorage.token;

export default {
  name: 'SupportView',
  components: {
    Button,
    Section
  },
  data() {
    return {
      ready: false,
      sshSupportEnabled: false,
      toggleSshSupportError: ''
    };
  },
  computed: {
    description() {
      return marked.parse(this.$t('support.help.description', {
        docsLink: 'https://docs.cloudron.io/?support_view',
        packagingLink: 'https://docs.cloudron.io/custom-apps/tutorial/?support_view',
        forumLink: 'https://forum.cloudron.io/'
      }));
    }
  },
  methods: {
    async toggleSshSupport() {
        this.toggleSshSupportError = '';

        const res = await fetcher.post(`${API_ORIGIN}/api/v1/support/remote_support`, { enable: !this.sshSupportEnabled }, { access_token: accessToken });
        if (res.status === 412 || res.status === 417) this.toggleSshSupportError = res.body;
        else if (res.status !== 202) console.error(res.body);

        this.sshSupportEnabled = !this.sshSupportEnabled;
    }
  },
  async mounted() {
    const response = await fetcher.get(`${API_ORIGIN}/api/v1/support/remote_support`, { access_token: accessToken });
    this.sshSupportEnabled = response.body.enabled;
    this.ready = true;
  }
};

</script>

<template>
  <div class="content">
    <h1 class="section-header">{{ $t('support.title') }}</h1>

    <Section :title="$t('support.help.title')">
      <div v-html="description"></div>
    </Section>

    <Section :title="$t('support.remoteSupport.title')">
      <h2 class="text-center" v-show="!ready"><i class="fa fa-circle-notch fa-spin"></i></h2>
      <div v-show="ready">
        <p>{{ $t('support.remoteSupport.description') }}</p>
        <b>{{ $t('support.remoteSupport.warning') }}</b>
        <br/>
        <br/>
        <b class="pull-left text-danger text-bold" v-show="toggleSshSupportError">{{ toggleSshSupportError }}</b>
        <Button :danger="sshSupportEnabled ? true : null" @click="toggleSshSupport()">{{ sshSupportEnabled ? $t('support.remoteSupport.disableAction') : $t('support.remoteSupport.enableAction') }}</Button>
      </div>
    </Section>
  </div>
</template>
