<template>
  <div>
    <PrimeFloatLabel class="mb-1">
      Resolution
    </PrimeFloatLabel>
    <PrimeSelectButton
      v-model="resolution"
      :options="resolutionOptions"
      fluid
      option-label="label"
      option-value="value"
      :allow-empty="false"
    />
  </div>

  <div class="mt-4">
    <PrimeFloatLabel class="mb-1">
      FPS
    </PrimeFloatLabel>
    <PrimeSelectButton
      v-model="fps"
      :options="fpsOptions"
      fluid
      option-label="label"
      option-value="value"
      :allow-empty="false"
    />
  </div>

  <div class="mt-4">
    <PrimeFloatLabel class="mb-1">
      Codec
    </PrimeFloatLabel>
    <PrimeSelect
      v-model="codecPayloadType"
      :options="videoCodecs"
      fluid
      option-label="mimeType"
      option-value="preferredPayloadType"
      placeholder="Select codec"
    >
      <template #option="{ option }">
        <div class="w-full whitespace-normal">
          <p>{{ option.mimeType }}</p>
          <p class="text-muted-color text-xs break-words">
            {{ option.parameters }}
          </p>
        </div>
      </template>
    </PrimeSelect>
  </div>

  <div class="text-right mt-8">
    <PrimeButton severity="success" @click="share">
      Share screen
    </PrimeButton>
  </div>
</template>

<script setup lang="ts">
import type { RtpCodecCapability } from 'mediasoup-client/types'
import { StorageSerializers, useLocalStorage } from '@vueuse/core'

export interface ShareSettings {
  resolution: number
  fps: number
  codec?: RtpCodecCapability
}

const emit = defineEmits<{
  share: [ShareSettings]
}>()

const mediasoup = useMediasoup()

const resolutionOptions = [
  {
    label: '720p',
    value: 720,
  },
  {
    label: '1080p',
    value: 1080,
  },
  {
    label: '1440p',
    value: 1440,
  },
]

const fpsOptions = [5, 30, 60].map((value) => {
  return {
    label: value.toString(),
    value,
  }
})

const videoCodecs = computed(() => {
  return (mediasoup.rtpCapabilities.value?.codecs ?? []).filter((codec) => {
    return codec.kind === 'video' && codec.mimeType !== 'video/rtx'
  })
})

const fps = useLocalStorage<number>(
  'SHARE_FPS',
  30,
  {
    serializer: StorageSerializers.number,
  },
)

const resolution = useLocalStorage<number>(
  'SHARE_RESOLUTION',
  1080,
  {
    serializer: StorageSerializers.number,
  },
)

const codecPayloadType = useLocalStorage<number>(
  'SHARE_CODEC_PAYLOAD_TYPE',
  (videoCodecs.value.find(codec => codec.mimeType === 'video/H264') ?? videoCodecs.value[0])?.preferredPayloadType ?? -1,
  {
    serializer: StorageSerializers.number,
  },
)

function share() {
  emit('share', {
    resolution: resolution.value,
    fps: fps.value,
    codec: videoCodecs.value.find(codec => codec.preferredPayloadType === codecPayloadType.value),
  })
}
</script>

<style lang="scss">

</style>
