import { useEditor } from "@/modules/editor";
import { defineComponent } from "vue";
import { string } from "vue-types";
import { useCompData } from ".";
import { View } from "../View";
import { useImage } from "./useImage";

export const Component = defineComponent({
  props: {
    compId: string().isRequired,
  },
  setup(props) {
    const comp = useCompData(props.compId);
    const { store, controls } = useEditor();
    const img = useImage(() => ({ value: comp.value, size: comp.layout.size.slice(0, 2) as number[] }));

    async function changeVal() {
      if (!store.isEditMode) return;
      const url = await controls.pickCtrl.pickOneImage();
      if (!url) return;

      comp.value.url = url;
      comp.value.x = 0;
      comp.value.y = 0;
      comp.value.s = 1;
    }

    return () => (
      <View
        class="overflow-hidden"
        compId={props.compId}
        onDblclick={changeVal}
      >
        <img
          crossorigin="anonymous"
          class="w-full h-full pointer-events-none"
          src={img.url}
          style={img.style}
        />
      </View>
    );
  },
});
