import { defineComponent, ref, watch } from "vue";
import { string } from "vue-types";
import { useCompData } from ".";
import { View } from "../View";
import { useEditor } from "@/modules/editor";
import { IconPicture } from "@queenjs/icons";
import { css } from "@linaria/core";

export const Component = defineComponent({
  props: {
    compId: string().isRequired,
  },
  setup(props) {
    const { store, controls, actions } = useEditor();
    const comp = useCompData(props.compId);
    const { value } = comp;
    const videoRef = ref();

    async function changeVal() {
      try {
        const url = await controls.pickCtrl.pickOneImage();
        if (!url) return;
        value.url = url;
      } catch (error) {
        console.log(error);
      }
    }

    watch(
      () => [value.ratio],
      () => {
        const { videoWidth, videoHeight } = videoRef.value;
        const t = value.ratio || videoWidth / videoHeight;
        comp.setH(comp.getW() / t);
        actions.onCompLayoutUpdated(comp);
      }
    );

    return () => {
      const options: any = {};
      if (value.autoplay) options.autoplay = true;
      if (value.loop) options.loop = true;
      if (value.controls) options.controls = true;

      return (
        <View class={rootCls} compId={props.compId}>
          <video
            ref={videoRef}
            key={value.url}
            class="w-full object-cover"
            style={{ aspectRatio: value.ratio }}
            {...options}
          >
            <source src={value.url}></source>
          </video>
          {store.isEditMode && (
            <IconPicture class={btnCls} onClick={changeVal} />
          )}
        </View>
      );
    };
  },
});

const btnCls = css`
  display: none;
  position: absolute;
  top: 50%;
  left: 50%;
  padding: 20px;
  font-size: 37.5px;
  color: #666;
  border-radius: 50%;
  background-color: rgba(255, 255, 255, 0.7);
  transform: translate(-50%, -50%);
  @apply shadow;
`;

const rootCls = css`
  &:hover {
    .${btnCls} {
      display: block;
    }
  }
`;
