<script setup>

import { ref, onMounted } from 'vue';
import { Switch } from '@cloudron/pankow';
import { ISTATES } from '../../constants.js';
import SettingsItem from '../SettingsItem.vue';
import AppsModel from '../../models/AppsModel.js';

const { app } = defineProps([ 'app' ]);

const appsModel = AppsModel.create();

const hasOptionalTurn = ref(app.manifest.addons?.turn?.optional);
const turnEnabled = ref(false);
const turnBusy = ref(false);

async function onTurnChange(value) {
  turnBusy.value = true;

  const [error] = await appsModel.configure(app.id, 'turn', { enable: value });
  if (error) {
    turnBusy.value = false;
    turnEnabled.value = !value;
    return console.error(error);
  }

  turnBusy.value = false;
}

const hasOptionalRedis = ref(app.manifest.addons?.redis?.optional);
const redisEnabled = ref(false);
const redisBusy = ref(false);

async function onRedisChange(value) {
  redisBusy.value = true;

  const [error] = await appsModel.configure(app.id, 'redis', { enable: value });
  if (error) {
    redisBusy.value = false;
    redisEnabled.value = !value;
    return console.error(error);
  }

  redisBusy.value = false;
}

onMounted(() => {
  turnEnabled.value = !!app.enableTurn;
  redisEnabled.value = !!app.enableRedis;
});

</script>

<template>
  <div>
    <SettingsItem v-if="hasOptionalTurn">
      <div>
        <label>{{ $t('app.turn.title') }} <sup><a href="https://docs.cloudron.io/apps/#turn" class="help" target="_blank"><i class="fa fa-question-circle"></i></a></sup></label>
        <div>{{ $t('app.turn.info') }}</div>
      </div>
      <Switch @change="onTurnChange" v-model="turnEnabled" :disabled="turnBusy || (app.error && app.error.installationState !== ISTATES.PENDING_SERVICES_CHANGE) || app.taskId"/>
    </SettingsItem>

    <SettingsItem v-if="hasOptionalRedis">
      <div>
        <label>{{ $t('app.redis.title') }} <sup><a href="https://docs.cloudron.io/apps/#redis" class="help" target="_blank"><i class="fa fa-question-circle"></i></a></sup></label>
        <div>{{ $t('app.redis.info') }}</div>
      </div>
      <Switch @change="onRedisChange" v-model="redisEnabled" :disabled="redisBusy || (app.error && app.error.installationState !== ISTATES.PENDING_SERVICES_CHANGE) || app.taskId"/>
    </SettingsItem>
  </div>
</template>
