<script setup lang="ts">
import { ref, watch, onMounted } from 'vue'
import type ISlice from '@/models/ISlice'

const props = defineProps<{ slices: ISlice[] }>()
const chart = ref<SVGSVGElement | null>(null)

const getCoordinatesForPercent = (percent: number): [number, number] => [
  Math.cos(2 * Math.PI * percent),
  Math.sin(2 * Math.PI * percent)
]

const clearSvg = () => {
  const svg = chart.value
  if (!svg) return
  while (svg.lastChild) svg.removeChild(svg.lastChild)
}

const constructChart = () => {
  const svg = chart.value
  if (!svg) return
  clearSvg()
  let cumulativePercent = 0
  props.slices.forEach((slice) => {
    const [startX, startY] = getCoordinatesForPercent(cumulativePercent)
    cumulativePercent += slice.percent
    const [endX, endY] = getCoordinatesForPercent(cumulativePercent)
    const largeArcFlag = slice.percent > 0.5 ? 1 : 0
    const pathData = [
      `M ${startX} ${startY}`,
      `A 1 1 0 ${largeArcFlag} 1 ${endX} ${endY}`,
      `L 0 0`
    ].join(' ')
    const pathEl = document.createElementNS('http://www.w3.org/2000/svg', 'path')
    pathEl.setAttribute('d', pathData)
    pathEl.setAttribute('fill', slice.color)
    svg.appendChild(pathEl)
  })
}

onMounted(constructChart)
watch(() => props.slices, constructChart, { deep: true })
</script>

<template>
  <svg
    id="chart-pie"
    ref="chart"
    class="chart-pie"
    viewBox="-1 -1 2 2"
  />
</template>

<style scoped>
.chart-pie {
  transform: rotate(-90deg);
  max-width: 400pt;
}
</style>
