<template>
  <div class="elem-composition-element elem-composition-element-edit">
    <element-resize
      v-model="elemData"
      :class="{ 'element-resize-act': curElement.id === data.id }"
      :active="active"
      :transform-fit="transformFit"
      :element-pk="data.id"
      isCompact
      @resize-over="resizeOver"
      @on-click="activeCurElement"
    >
      <div
        :class="classes"
        :style="styles"
        :id="data.id"
        :data-type="data.type"
      >
        <component :is="compName" :data="data"></component>
      </div>
    </element-resize>
  </div>
</template>

<script>
import { mapState, mapMutations } from "vuex";
import { objAssign } from "../../plugins/utils";

import ElementResize from "../../components/common/ElementResize";
import ElemText from "../text/ElemText";
import ElemImage from "../image/ElemImage";
import ElemLine from "../line/ElemLine";
import ElemLines from "../lines/ElemLines";
import ElemGrids from "../grids/ElemGrids";

export default {
  name: "elem-composition-element-edit",
  components: {
    ElemText,
    ElemImage,
    ElemLine,
    ElemLines,
    ElemGrids,
    ElementResize
  },
  props: {
    data: {
      type: Object
    },
    transformFit: {
      type: Function,
      default() {
        return {};
      }
    }
  },
  data() {
    return {
      elemData: {
        x: 0,
        y: 0,
        w: 0,
        h: 0
      },
      styles: {},
      actives: {
        TEXT: ["r", "rb", "b", "lb", "l", "lt", "t", "rt"],
        IMAGE: ["r", "rb", "b", "lb", "l", "lt", "t", "rt"],
        LINES: [],
        GRIDS: [],
        LINE_HORIZONTAL: ["l", "r"],
        LINE_VERTICAL: ["t", "b"]
      }
    };
  },
  computed: {
    ...mapState("card", ["curElement"]),
    compName() {
      if (this.data.type.includes("LINE_")) return "elem-line";
      return `elem-${this.data.type.toLowerCase()}`;
    },
    elementName() {
      return this.data.type.toLowerCase().replace("_", "-");
    },
    classes() {
      return [
        "composition-element-body",
        `composition-element-${this.elementName}`
      ];
    },
    active() {
      return this.actives[this.data.type];
    }
  },
  created() {
    this.init();
  },
  methods: {
    ...mapMutations("card", ["setCurElement"]),
    init() {
      this.elemData = objAssign(this.elemData, this.data);
      this.styles = {
        left: this.data.x + "px",
        top: this.data.y + "px",
        width: this.data.w + "px",
        height: this.data.h + "px"
      };
    },
    resizeOver() {
      this.$emit("resize-over", Object.assign({}, this.data, this.elemData));
    },
    activeCurElement() {
      this.setCurElement(this.data);
    }
  }
};
</script>
