<script setup lang="ts">
import { getFilename } from '../pattern';
import { getColorHexFromRal, getColorNameFromRal } from '../ral';

const props = defineProps(['cb', 'name', 'color', 'pattern', 'type', 'disabled', 'goto_cam', 'goto_target'])

const goto_cam = use_goto_camera()
const goto_target = use_goto_target()
const open_calc = use_open_calc()

const picker = ref()
const is_open = ref<boolean>(open_calc.value.includes(props.name))

const toggleOpen = (value: boolean = !is_open) => {
    is_open.value = value
    if (value == true) open_calc.value = [props.name]
    else if (value == false && open_calc.value.includes(props.name)) open_calc.value = []

    if (value == true && props.goto_cam) goto_cam.value = props.goto_cam
    if (value == true && props.goto_target) goto_target.value = props.goto_target
}

const onClick = (color: string) => {
    if (props.cb) {
        props.cb(color)
    }
}

watch(open_calc, () => {
    if (open_calc.value.includes(props.name) && is_open.value !== true) {
        is_open.value = true
    } else if (!open_calc.value.includes(props.name) && is_open.value !== false) {
        is_open.value = false
    }
})
</script>
<template>
    <div class="picker" :class="[{
        'picker_open': is_open,
        'picker_disabled': props.disabled,
    }]" ref="picker">
        <div class="picker-input">
            <template v-if="props.type == 'color'">
                <div @click="toggleOpen(!is_open)"
                    :style="[{ color: contrastColor(props.color), backgroundColor: getColorHexFromRal(props.color) ?? 'transparent' }]">
                    <span>
                        {{ getColorNameFromRal(props.color) }}
                    </span>
                    <Icon class="picker-button" :name="is_open ? 'mdi:chevron-up' : 'mdi:chevron-down'" />
                </div>
            </template>
            <template v-else>
                <div @click="toggleOpen(!is_open)" :style="getFilename(props.pattern) ? [{
                    backgroundImage: `url(${getFilename(props.pattern)})`,
                    backgroundSize: 'contain',
                    color: 'transparent'
                }] : []">
                    <span>
                        {{ props.pattern }}
                    </span>
                    <Icon class="picker-button" :name="is_open ? 'mdi:chevron-up' : 'mdi:chevron-down'" />
                </div>
            </template>
        </div>

        <div class="picker-changer flex flex-wrap" v-if="is_open">
            <template v-if="props.type == 'color'">
                <DropdownColor :cb="onClick" />
            </template>
            <template v-else>
                <DropdownList :cb="onClick" :patterns="props.type" />
            </template>
        </div>
    </div>
</template>
<style scoped>
.color_picker-selected:not([style*=color]) {
    background-image: conic-gradient(from 50deg, orange, yellow, green, cyan, blue, violet)
}
</style>