<script setup>

import { ref, onMounted } from 'vue';
import { Button, FormGroup, Checkbox } from 'pankow';
import AppsModel from '../../models/AppsModel.js';

const props = defineProps([ 'app' ]);

const appsModel = AppsModel.create();

function onAddDisableIndexing() {
  robotsTxt.value = '# Disable search engine indexing\n\nUser-agent: *\nDisallow: /';
}

const busy = ref(false);
const robotsTxt = ref('');
const csp = ref('');
const hstsPreload = ref(false);

async function onSubmit() {
  busy.value = true;

  const data = {
    robotsTxt: robotsTxt.value || null, // empty string resets
    csp: csp.value || null, // empty string resets
    hstsPreload: hstsPreload.value,
  };

  const [error] = await appsModel.configure(props.app.id, 'reverse_proxy', data);
  if (error) return console.error(error);

  busy.value = false;
}

onMounted(() => {
  robotsTxt.value = props.app.reverseProxyConfig.robotsTxt || '';
  csp.value = props.app.reverseProxyConfig.csp || '';
  hstsPreload.value = props.app.reverseProxyConfig.hstsPreload || false;
});

</script>

<template>
  <div>
    <form @submit.prevent="onSubmit()" autocomplete="off">
      <fieldset :disabled="busy || app.error">
        <input style="display: none;" type="submit" />

        <FormGroup>
          <label for="robotsTxtInput" style="display: flex; justify-content: space-between;">
            <span>{{ $t('app.security.robots.title') }} <sup><a href="https://docs.cloudron.io/apps/#robotstxt" class="help" target="_blank"><i class="fa fa-question-circle"></i></a></sup></span>
            <Button small outline @click="onAddDisableIndexing()">{{ $t('app.security.robots.disableIndexingAction') }}</Button>
          </label>
          <textarea id="robotsTxtInput" style="white-space: pre-wrap; font-family: monospace;" v-model="robotsTxt" rows="10" :placeholder="$t('app.security.robots.txtPlaceholder')"></textarea>
        </FormGroup>

        <FormGroup>
          <label for="cspInput">{{ $t('app.security.csp.title') }} <sup><a href="https://docs.cloudron.io/apps/#custom-csp" class="help" target="_blank"><i class="fa fa-question-circle"></i></a></sup> </label>
          <p>{{ $t('app.security.csp.description') }}</p>
          <textarea id="cspInput" style="white-space: pre-wrap; font-family: monospace;" v-model="csp" placeholder="default-src 'self'; frame-ancestors 'none';" rows="2"></textarea>
        </FormGroup>

        <br/>

        <Checkbox v-model="hstsPreload" :label="$t('app.security.hstsPreload')"/> <sup><a href="https://docs.cloudron.io/apps/#hsts-preload" class="help" target="_blank"><i class="fa fa-question-circle"></i></a></sup>

        <br/>
        <br/>

        <Button @click="onSubmit()" :loading="busy" :disabled="busy">{{ $t('app.security.csp.saveAction') }}</Button>
      </fieldset>
    </form>
  </div>
</template>
