<template>
  <ColorPicker v-model="currentValue" :format="format" :disabled="disabled" :placement="placement" :transfer="transfer" @on-change="colorChange" v-if="type==='dropdown'">
    <slot></slot>
  </ColorPicker>
  <ColorPanel v-model="currentValue" :format="format" :disabled="disabled" @on-change="colorChange" v-else/>
</template>

<script>
import { getCurrentInstance } from "vue";
import ColorPicker from './color-picker.vue';
import ColorPanel from './ColorPanel.vue';
import util from '../../libs/util';
export default {
  components: {ColorPicker, ColorPanel},
  props: {
    modelValue: {
      type: String,
      default: undefined,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    placement: {
      type: String,
      validator(value) {
        return util.oneOf(value, [
          "top",
          "top-start",
          "top-end",
          "bottom",
          "bottom-start",
          "bottom-end",
          "left",
          "left-start",
          "left-end",
          "right",
          "right-start",
          "right-end",
        ]);
      },
      default: "bottom",
    },
    transfer: {
      type: Boolean,
      default() {
        const global = getCurrentInstance().appContext.config.globalProperties;
        return !global.$VIEWUI || global.$VIEWUI.transfer === ""
          ? false
          : global.$VIEWUI.transfer;
      },
    },
    format: {
      type: String,
      validator(value) {
        return util.oneOf(value, ["hsl", "hsv", "hex", "rgb"]);
      },
      default: undefined,
    },
    type: {
      type: String,
      validator(value) {
        return util.oneOf(value, [
          "dropdown",
          "panel"
        ]);
      },
      default: 'dropdown'
    }
  },
  emits: [
    "on-change",
    "update:modelValue",
  ],
  data() {
    return {
      currentValue: this.modelValue || ""
    };
  },
  methods: {
    colorChange(color) {
      this.currentValue = color;
      this.$emit("update:modelValue", color);
      this.$emit("on-change", color);
    }
  },
  watch: {
    modelValue(newVal) {
      this.currentValue = newVal;
    }
  }
}
</script>