<template>
  <div class="flex-grow-1 vb-body-left" style="position: relative;">
    <Button
      v-if="this.selectedWidget.parentRow != null"
      style="height: 23px; background-color: lightblue; border-radius: 4px; border: none; position: absolute; right: 3px; top: 3px"
      @click="selectedWidget.parentRow = null, selectedWidget.column = null, selectedWidget.row = null"
    >X</Button>
    <div
      class="flex-grow-1 vb-body-left"
      @click="backgroundClicked"
      @mouseover="updateWidgetHoverIndex($event.target.id)"
      @mouseleave="mouseHasLeft()"
      :id="JSON.stringify({ parentRow: null, column: null, row: null })"
    >
      <vue-perfect-scrollbar class="scroll-area">
        <div class="vb-bls" v-if="widgetType.length == 0">
          <span>
            <!-- <a href="#" @click="$emit('addFirstWidget')">Add Row</a> -->
            Please add column
          </span>
        </div>
        <div id="getemail" style="margin: 20px 0px;">
          <table style="font-family: Arial;" width="100%">
            <tr>
              <td
                v-droppable
                @drag-enter="onDragEnter"
                @drag-leave="onDragLeave"
                :id="JSON.stringify({ parentRow: null, column: null, row: null })"
                style="width: 20px"
              ></td>
              <td>
                <Container
                  lock-axis="y"
                  drag-handle-selector=".column-drag-handle"
                  @drop="onDrop"
                  @drop-ready="onDropReady"
                >
                  <Draggable
                    v-for="(parentRow, index) in widgetType"
                    :key="index"
                    style="overflow: visible;"
                  >
                    <div class="draggable-item">
                      <table
                        id="2"
                        :style="{'position': 'relative', 'width': '100%', 'backgroundColor' : parentRow.style[2].bgcolor }"
                      >
                        <b-btn
                          class="column-drag-handle moveBtn"
                          style="z-index: 21"
                          v-if="JSON.stringify(selectedWidget) == JSON.stringify({ parentRow: index, column: null, row: null })"
                        >
                          <span class="ti-move"></span>
                        </b-btn>
                        <tr>
                          
                          <td
                            id="padding id"
                            :style="{'padding': parentRow.style[1].padding + 'px',
                            'paddingRight': parentRow.style[1].paddingRight + 'px',
                            'paddingLeft': parentRow.style[1].paddingLeft + 'px',
                            'paddingTop': parentRow.style[1].paddingTop + 'px',
                            'paddingBottom': parentRow.style[1].paddingBottom + 'px'}"
                          >
                            <!-- always displays column parentRowWidget -->
                            <component
                              :dragWidgetType="dragWidgetType"
                              :widgetHoverIndex="widgetHoverIndex"
                              :selectedDropWidget="selectedDropWidget"
                              :hasDragEnded="hasDragEnded"
                              :isDraging="isDraging"
                              :widgetType="widgetType"
                              :is="parentRow.component"
                              :NewStyle="widgetType[index].style"
                              :selectedWidget="selectedWidget"
                              :index="{ parentRow: index, column: null, row: null }"
                              :widgetDidMove="widgetDidMove"
                              v-on:typedText="updateWigetValue($event, index)"
                              v-on:DeleteWidget="DeleteWidget(index)"
                              v-on:selected="selected({ parentRow: index, column: null, row: null })"
                              v-on:changeSelectedDropWidget="changeSelectedDropWidget($event)"
                            >
                              <td
                                id="tabletest"
                                v-for="(column, columnIndex) in parentRow.columns"
                                :key="columnIndex"
                                valign="top"
                                :style="{'width': column.style[2]}"
                              >
                                <component
                                  :placeholderStyle="column.style"
                                  :dragWidgetType="dragWidgetType"
                                  :widgetType="widgetType"
                                  :widgetHoverIndex="widgetHoverIndex"
                                  :is="column.component"
                                  :index="{ parentRow: index, column: columnIndex, row: null }"
                                  :selectedDropWidget="selectedDropWidget"
                                  v-on:changeSelectedDropWidget="changeSelectedDropWidget($event)"
                                >
                                  <table
                                    id="test3"
                                    v-if="column.rows.length > 0"
                                    style="width: 100%; height: 100%;"
                                  >
                                    <tr
                                      v-for="(rows, rowIndex) in column.rows"
                                      :key="rowIndex"
                                      class="childDiv"
                                    >
                                      <td style="position: relative">
                                        <div
                                          id="dragHandle"
                                          class="dragHandleBtn"
                                          v-if="JSON.stringify(selectedWidget) == JSON.stringify({ parentRow: index, column: columnIndex, row: rowIndex })"
                                          v-draggable
                                          @drag-end="$emit('onDragEnd', { parentRow: index, column: columnIndex, row: rowIndex })"
                                          @drag-start="$emit('onDragStart', { parentRow: index, column: columnIndex, row: rowIndex })"
                                        >
                                          <span class="ti-move" style="color: #FFF;"></span>
                                        </div>
                                        <editCard
                                          :dragWidgetType="dragWidgetType"
                                          :widgetType="widgetType"
                                          :widgetHoverIndex="widgetHoverIndex"
                                          :selectedDropWidget="selectedDropWidget"
                                          :hasDragEnded="hasDragEnded"
                                          :isDraging="isDraging"
                                          :NewStyle="rows.style"
                                          :widText="rows"
                                          :selectedWidget="selectedWidget"
                                          :index="{ parentRow: index, column: columnIndex, row: rowIndex }"
                                          :widgetDidMove="widgetDidMove"
                                          v-on:typedText="updateWigetValue($event, index)"
                                          v-on:DeleteWidget="DeleteWidget($event)"
                                          v-on:selected="selected({ parentRow: index, column: columnIndex, row: rowIndex })"
                                          v-on:changeSelectedDropWidget="changeSelectedDropWidget($event)"
                                          v-on:addToBottom="addToBottom($event)"
                                        >
                                          <component
                                            :dragWidgetType="dragWidgetType"
                                            :widgetType="widgetType"
                                            :widgetHoverIndex="widgetHoverIndex"
                                            :selectedDropWidget="selectedDropWidget"
                                            :hasDragEnded="hasDragEnded"
                                            :isDraging="isDraging"
                                            :is="rows.component"
                                            :NewStyle="rows.style"
                                            :widText="rows"
                                            :selectedWidget="selectedWidget"
                                            :index="{ parentRow: index, column: columnIndex, row: rowIndex }"
                                            :widgetDidMove="widgetDidMove"
                                            v-on:typedText="updateWigetValue($event, index)"
                                            v-on:DeleteWidget="DeleteWidget($event)"
                                            v-on:selected="selected({ parentRow: index, column: columnIndex, row: rowIndex })"
                                            v-on:changeSelectedDropWidget="changeSelectedDropWidget($event)"
                                            v-on:addToBottom="addToBottom($event)"
                                          ></component>
                                        </editCard>
                                      </td>
                                    </tr>
                                  </table>
                                </component>
                              </td>
                            </component>
                          </td>
                        </tr>
                      </table>
                    </div>
                  </Draggable>
                </Container>
              </td>
              <td
                v-droppable
                @drag-enter="onDragEnter"
                @drag-leave="onDragLeave"
                :id="JSON.stringify({ parentRow: null, column: null, row: null })"
                style="width: 20px"
              ></td>
            </tr>
          </table>
          <v-style type="text/css">

            button {
            border: none;
            }
            p{
            margin:0;
            line-height: unset !important;
            }
            table{
            border-collapse: collapse;
            }
            tr, td{
            border:0px;
            }
          </v-style>
        </div>
      </vue-perfect-scrollbar>
    </div>
  </div>
</template>

<script>
import juice from "juice";

import editCard from "./widgets/editCard.vue";

import RowProperties from "@/temp/email/tools/row-properties.vue";
import ColProperties from "@/temp/email/tools/col-properties.vue";

import parentRowWidget from "@/temp/email/widgets/parentRowWidget";
import columnPlaceholder from "@/temp/email/widgets/columnPlaceholder";
import buttonWidget from "@/temp/email/widgets/buttonWidget";
import dividerWidget from "@/temp/email/widgets/dividerWidget";
import htmlWidget from "@/temp/email/widgets/htmlWidget";
import imageWidget from "@/temp/email/widgets/imageWidget";
import textWidget from "@/temp/email/widgets/textWidget";

import { Draggable, Container } from "@/temp/webform/MainFileImports";
import parentRowWidgetVue from "./widgets/parentRowWidget.vue";
import { constants } from "os";
export default {
  name: "emailLeft",
  components: {
    RowProperties,
    ColProperties,
    Draggable,
    Container,
    parentRowWidget,
    columnPlaceholder,
    buttonWidget,
    dividerWidget,
    htmlWidget,
    imageWidget,
    textWidget,
    editCard
  },
  props: {
    widgetType: {
      type: Array
    },
    hasDragEnded: {
      type: Boolean
    },
    dragWidgetType: {
      type: String
    },
    selectedWidget: Object,
    emailHTML: Object
  },
  data: function() {
    return {
      widgetTypeCopy: [],
      widgetHoverIndex: {
        parentRow: null,
        column: null,
        row: null
      },
      myData: "hasan",
      widget: [],
      inputText: "",
      edit: false,
      delete: false,
      selectDismiss: false,
      selectedWidgetTapped: false,
      widgetDidMove: false,
      dropEnd: false,
      isDraging: false,
      selectedDropWidget: {
        parentRow: null,
        column: null,
        row: null
      },
      testStyle: "20px"
    };
  },
  computed: {
    getKey: function() {
      return this.widgetType.length;
    }
  },
  created() {
    this.widgetTypeCopy = JSON.parse(JSON.stringify(this.widgetType));
  },
  updated() {
    if (
      JSON.stringify(this.widgetTypeCopy) != JSON.stringify(this.widgetType)
    ) {
      this.widgetTypeCopy = JSON.parse(JSON.stringify(this.widgetType));

      this.emailHTML.htmlData = document
        .getElementById("getemail")
        .innerHTML.replace(/class="hoverBox"/g, 'style="display: none;"')
        .replace(
          /class="column-drag-handle moveBtn"/g,
          'style="display: none;"'
        )
        .replace(/id="dragHandle"/g, 'style="display: none;"')
        .replace(
          /id="{&quot;parentRow&quot;:null,&quot;column&quot;:null,&quot;row&quot;:null}"/g,
          ""
        )
        .replace(
          /id="{&quot;parentRow&quot;:0,&quot;column&quot;:0,&quot;row&quot;:null}"/g,
          ""
        )
        .replace(
          /id="{&quot;parentRow&quot;:0,&quot;column&quot;:null,&quot;row&quot;:null}"/g,
          ""
        )
        .replace(/class="draggable-item"/g, "")
        .replace(/class="smooth-dnd-draggable-wrapper"/g, "")
        .replace(
          /style="width: 100%; padding: 0px; border: 0px solid blue;"/g,
          ""
        )
        .replace(/class="test1"/g, "")
        .replace(/style="border: 0px; width: 20px;"/g, "")
        .replace(/style="border: 0px; width: 20px;" width="20"/g, "");

      // console.log(juice(this.emailHTML.htmlData))
    }

    if (this.dropEnd) {
      setTimeout(() => (this.widgetDidMove = false), 300);
    }
    if (this.hasDragEnded) {
      //console.log('drag ended');
      this.selectedDropWidget = {
        parentRow: null,
        column: null,
        row: null
      };
      this.$emit("changeHasDragEnded");
    }
  },
  methods: {
    mouseHasLeft() {
      this.widgetHoverIndex = {
        parentRow: null,
        column: null,
        row: null
      };
    },
    cssProps: function() {
      return {
        width: "100%",
        "--padding": "10px"
      };
    },
    passOn(value) {
      this.$emit("changeDropValue", value);
    },
    addToBottom(value) {
      this.$emit("addToBottom", value);
    },
    updateWidgetHoverIndex(event) {
      if (event.includes("parentRow")) {
        // console.log(event);
        this.widgetHoverIndex = JSON.parse(event);
      }
    },
    changeSelectedDropWidget(index) {
      // console.log('changeSelectedDropWidget')
      this.selectedDropWidget = index;
      this.$emit("selectedDropWidget", index);
    },
    onDragEnter() {
      this.isDraging = true;
      this.selectedDropWidget = {
        parentRow: null,
        column: null,
        row: null
      };
    },
    onDragDrop() {
      this.isDraging = false;
    },
    onDragLeave() {
      this.isDraging = false;
    },
    onDrop(dragResult) {
      const { removedIndex, addedIndex, payload } = dragResult;

      // this.widgetType = applyDrag(this.widgetType, dropResult);

      if (removedIndex == addedIndex) {
      } else {
        let payload = JSON.parse(JSON.stringify(this.widgetType[removedIndex]));

        payload.component = parentRowWidget;
        payload.columns.forEach(elem => {
          elem.component = columnPlaceholder;
          elem.rows.forEach(elem1 => {
            switch (elem1.type) {
              case "buttonWidget":
                elem1.component = buttonWidget;
                break;
              case "dividerWidget":
                elem1.component = dividerWidget;
                break;
              case "htmlWidget":
                elem1.component = htmlWidget;
                break;
              case "imageWidget":
                elem1.component = imageWidget;
                break;
              case "textWidget":
                elem1.component = textWidget;
                break;
            }
          });
        });

        if (removedIndex === null && addedIndex === null) {
        } else {
          let itemToAdd = payload;

          if (removedIndex !== null) {
            itemToAdd = this.widgetType.splice(removedIndex, 1)[0];
          }

          if (addedIndex !== null) {
            this.widgetType.splice(addedIndex, 0, itemToAdd);
          }
        }
      }
    },

    onDropReady() {
      this.widgetDidMove = true;
    },

    updateWigetValue: function(value, key) {
      //this.widgetType[key].value = value;
    },
    DeleteWidget: function() {
      this.delete = true;
    },
    selected: function(key) {
      //console.log(key);

      if (this.delete) {
        this.delete = false;
        this.edit = false;
        if (key.row == null) {
          this.widgetType.splice(this.selectedWidget.parentRow, 1);
        } else {
          this.widgetType[this.selectedWidget.parentRow].columns[
            this.selectedWidget.column
          ].rows.splice(this.selectedWidget.row, 1);
        }

        this.selectedWidget.parentRow = null;
        this.selectedWidget.column = null;
        this.selectedWidget.row = null;
      } else if (
        JSON.stringify(this.selectedWidget) ==
        JSON.stringify({
          parentRow: null,
          column: null,
          row: null
        })
      ) {
        this.selectedWidgetTapped = true;
        this.selectedWidget.parentRow = key.parentRow;
        this.selectedWidget.column = key.column;
        this.selectedWidget.row = key.row;
        //this.$set(this.widgetType[key].style, [0], "white");
        this.edit = !this.edit;
      } else if (JSON.stringify(this.selectedWidget) != JSON.stringify(key)) {
      } else {
        this.selectedWidgetTapped = true;
        //this.$set(this.widgetType[this.selectedWidget].style, [0], "white");
        this.selectedWidget.parentRow = key.parentRow;
        this.selectedWidget.column = key.column;
        this.selectedWidget.row = key.row;
        //this.$set(this.widgetType[key].style, 0, "white");
      }
      this.$emit("selectedWidget", this.selectedWidget);
      //console.log(this.selectedWidget.parentRow);
    },
    selectedComplete: function() {
      //this.$set(this.widgetType[this.selectedWidget].style, 0, "white");
      this.edit = !this.edit;
      this.selectedWidget = null;
      this.$emit("selectedWidget", null);
    },
    backgroundClicked: function() {
      if (!this.selectedWidgetTapped && this.selectedWidget != null) {
        //this.$set(this.widgetType[this.selectedWidget].style, [0], "white");
        this.edit = !this.edit;
        this.selectedWidget.parentRow = null;
        this.selectedWidget.column = null;
        this.selectedWidget.row = null;
        this.selectDismiss = false;
      } else if (this.selectedWidgetTapped) {
        this.selectedWidgetTapped = false;
      }
      this.$emit("selectedWidget", this.selectedWidget);
    }
  }
};
</script>

<style>
.parentRowStyle {
  padding: var(--padding);
}

.test1 {
  height: 5px;
  width: 100%;
  position: absolute;
  z-index: 3;
  top: 0px;
  left: 0px;
}

.dragHandleBtn {
  z-index: 15;
  height: 20px;
  padding-top: 1px;
  position: absolute;
  right: -20px;
  margin-top: auto;
  margin-bottom: auto;
  top: 0;
  bottom: 0;
  background-color: rgb(76, 185, 234);
  width: 20px;
  text-align: center;
  border-radius: 0px 10px 10px 0px;
}
</style>
