<template>
  <div>
    <span class="text-caption">{{ t('labels.opacity') }}</span>
    <v-slider
      :model-value="opacity"
      @update:model-value="setOpacity"
      hide-details
      min="0"
      max="100"
      thumb-color="primary"
      :thumb-label="label"
      thumb-size="16"
      step="1"
    >
      <template #prepend>
        <v-btn
          variant="text"
          icon="remove"
          density="compact"
          @click="decrement"
        />
      </template>
      <template #append>
        <v-btn
          variant="text"
          icon="add"
          density="compact"
          @click="increment"
        />
      </template>
    </v-slider>
  </div>
</template>

<script setup lang="ts">
import { useViewer3cr } from '@/composables/useViewer3cr';
import { clamp } from '@/functions/clamp';
import { ObjectColour } from '@3cr/types-ts';
import { DataOverlayMcad } from '@3cr/viewer-types-ts';
import { computed, ref } from 'vue';
import { useI18n } from 'vue-i18n';

interface Props {
  mcad: DataOverlayMcad;
}

const props = defineProps<Props>();

const { t } = useI18n();
const viewer3cr = useViewer3cr();

const label = ref<boolean | 'always'>(true);
const timeout = ref<number>();

const opacity = computed(() => Math.round(props.mcad.Colour.A * 100));

async function increment(): Promise<void> {
  await setOpacity(opacity.value + 1);
  showLabel();
}

async function decrement(): Promise<void> {
  await setOpacity(opacity.value - 1);
  showLabel();
}

function showLabel(): void {
  label.value = 'always';
  if (timeout.value) {
    clearTimeout(timeout.value);
  }
  timeout.value = setTimeout(() => (label.value = true), 1000);
}

async function setOpacity(value: number): Promise<void> {
  const message: ObjectColour = {
    Version: '0.0.0',
    Id: props.mcad.Id,
    Colour: {
      Version: '0.0.0',
      R: props.mcad.Colour.R,
      G: props.mcad.Colour.G,
      B: props.mcad.Colour.B,
      A: clamp(value, 0, 100) / 100,
    },
  };
  await viewer3cr.setMcadObjectColour({ message });
}
</script>
