import { getTouches, on, off } from "./utils";

export default {
  props: {
    focused: {
      type: Boolean,
      default: false,
    },
    value: {
      type: Object,
      default: undefined,
    },
  },
  inject: {
    ColorPanelInstance: {
      default: null,
    },
  },
  created() {
    if (this.focused) {
      setTimeout(() => this.$el.focus(), 1);
    }
  },
  beforeUnmount() {
    this.unbindEventListeners();
  },
  methods: {
    handleLeft(e) {
      this.handleSlide(e, this.left, "left");
    },
    handleRight(e) {
      this.handleSlide(e, this.right, "right");
    },
    handleUp(e) {
      this.handleSlide(e, this.up, "up");
    },
    handleDown(e) {
      this.handleSlide(e, this.down, "down");
    },
    handleMouseDown(e) {
      this.ColorPanelInstance.handleOnDragging(true);
      //this.handleInput(e);
      // window.addEventListener('mousemove', this.handleChange, false);
      // window.addEventListener('mouseup', this.handleMouseUp, false);
      on(window, "mousemove", this.handleInput);
      on(window, "mouseup", this.handleMouseUp);
    },
    handleMouseUp(e) {
      this.handleChange(e);
      this.unbindEventListeners();
    },
    unbindEventListeners() {
      // window.removeEventListener('mousemove', this.handleChange);
      // window.removeEventListener('mouseup', this.handleMouseUp);
      off(window, "mousemove", this.handleInput);
      off(window, "mouseup", this.handleMouseUp);
      // This timeout is required so that the click handler for click-outside
      // has the chance to run before the mouseup removes the dragging flag.
      setTimeout(() => this.ColorPanelInstance.handleOnDragging(false), 1);
    },
    getLeft(e) {
      if (typeof window === "undefined") return;
      const { container } = this.$refs;
      const xOffset =
        container.getBoundingClientRect().left + window.pageXOffset;
      const pageX = e.pageX || getTouches(e, "PageX");

      return pageX - xOffset;
    },
    getTop(e) {
      if (typeof window === "undefined") return;
      const { container } = this.$refs;
      const yOffset =
        container.getBoundingClientRect().top + window.pageYOffset;
      const pageY = e.pageY || getTouches(e, "PageY");

      return pageY - yOffset;
    },
  },
};
