<template>
  <div>
    <q-scroll-area
      :style="{ height: content_height + 'px' }"
      style="width: 20vw"
    >
      <q-tree ref="tree" :nodes="tree_nodes" node-key="uuid" labelKey="name">
        <template v-slot:default-header="prop">
          <q-item
            class="full-width"
            clickable
            :draggable="!prop.node.is_group"
            @dragstart="(evt) => onDragStart(evt, prop.node)"
            @dblclick="
              (evt) =>
                false && !prop.node.is_group && runPlan(prop.node.item_data)
            "
          >
            <q-item-section avatar>
              <q-icon
                :name="
                  prop.node.is_group
                    ? 'img:source_icon/group.png'
                    : 'img:new_icon/polling_icon.png'
                "
                color="orange"
                size="28px"
                class="q-mr-sm"
              />
            </q-item-section>
            <q-item-section>
              <div class="text-weight-bold text-primary">
                {{ prop.node.name }}
              </div>
            </q-item-section>
            <q-popup-proxy context-menu>
              <q-list>
                <q-item
                  v-if="
                    prop.node.name == $t('signal polling') ||
                    (prop.node.is_group && prop.node.item_data)
                  "
                  clickable
                  v-close-popup
                  v-ripple
                  @click="addPolling($event, prop.node.item_data)"
                >
                  <q-item-section avatar><q-icon name="add" /></q-item-section>
                  <q-item-section>{{ $t("add polling") }}</q-item-section>
                </q-item>
                <q-item
                  clickable
                  v-close-popup
                  v-if="
                    false &&
                    (prop.node.name == $t('signal polling') ||
                      (prop.node.is_group && prop.node.item_data))
                  "
                  v-ripple
                  @click="addPollingGroup($event, prop.node.item_data)"
                >
                  <q-item-section avatar
                    ><q-icon name="create_new_folder"
                  /></q-item-section>
                  <q-item-section>{{ $t("add group") }}</q-item-section>
                </q-item>

                <q-item
                  clickable
                  v-ripple
                  v-close-popup
                  v-if="!prop.node.is_group && prop.node.item_data"
                  @click="editPolling($event, prop.node.item_data)"
                >
                  <q-item-section avatar><q-icon name="edit" /></q-item-section>
                  <q-item-section>{{ $t("edit") }}</q-item-section>
                </q-item>

                <q-item
                  clickable
                  v-ripple
                  v-close-popup
                  v-if="prop.node.item_data"
                  @click="
                    (evt) => deleteItem(evt, prop.node.is_group, prop.node.uuid)
                  "
                >
                  <q-item-section avatar
                    ><q-icon color="red" name="delete"
                  /></q-item-section>
                  <q-item-section>{{ $t("delete") }} &nbsp;</q-item-section>
                </q-item>
              </q-list>
            </q-popup-proxy>
          </q-item>
        </template>
      </q-tree>
    </q-scroll-area>
  </div>
  <polling-setting-dialog ref="polling_setting_dialog" />
</template>

<script lang="ts">
import { defineComponent, computed, onMounted, ref, Ref, nextTick } from "vue";
import { useStore } from "src/store";
import { Common } from "src/common/Common";
import GlobalData from "src/common/GlobalData";
import { useQuasar } from "quasar";
import { useI18n } from "vue-i18n";
import EventBus, { EventNamesDefine } from "src/common/EventBus";
import { Protocol } from "src/entities/WSProtocol";
import { NotifyMessage } from "src/common/ClientConnection";
import {
  PollingEntity,
  PollingTreeItemEntity,
} from "src/entities/PollingEntity";
import PollingSettingDialog from "src/components/PollingSettingDialog.vue";

export default defineComponent({
  name: "ComponentPollingTree",
  components: {
    PollingSettingDialog,
  },

  setup() {
    const $store = useStore();
    const $q = useQuasar();
    const $t = useI18n();

    const tree_nodes = computed({
      get: () => $store.state.polling_tree,
      set: (val) => {},
    });

    const content_height = ref(0);

    const refresh_content_height = () => {
      content_height.value = window.innerHeight - 135;
    };
    refresh_content_height();

    EventBus.getInstance().on(EventNamesDefine.WindowResize, () => {
      refresh_content_height();
    });

    const tree: any | null = ref(null);
    const polling_setting_dialog: Ref<any> = ref(null);

    onMounted(async () => {
      while (!tree.value?.nodes?.length) {
        await Common.waitFor(100);
      }
      tree.value?.setExpanded("", true);
    });

    return {
      tree,
      polling_setting_dialog,
      tree_nodes,
      content_height,
      loga(a: any) {
        console.log(a);
      },
      async deleteItem(
        evt: PointerEvent | null,
        is_group: boolean,
        uuid: string
      ) {
        let success = false;
        if (is_group) {
          let response = await GlobalData.getInstance()
            .getCurrentClient()
            ?.deletePollingGroup(uuid);
          if (response) {
            success = response.success;
          }
        } else {
          let response = await GlobalData.getInstance()
            .getCurrentClient()
            ?.deletePolling(uuid);
          if (response) {
            success = response.success;
          }
        }
        $q.notify({
          color: success ? "positive" : "negative",
          icon: success ? "done" : "warning",
          message:
            $t.t("delete") + (success ? $t.t("success") : $t.t("fail")) + "!",
          position: "top",
          timeout: 1500,
        });
      },
      onDragStart(e: DragEvent, node: PollingTreeItemEntity) {
        e.dataTransfer?.setData("uuid", node.uuid);
        e.dataTransfer?.setData("type", "polling");
        e.dataTransfer?.setData("node_object", JSON.stringify(node));
        if (e.dataTransfer) {
          e.dataTransfer.dropEffect = "move";
        }
      },
      async editPolling(event: MouseEvent, data: PollingEntity) {
        if (polling_setting_dialog.value) {
          const result = await polling_setting_dialog.value.showDialogAsync(
            data.name,
            data.polling_signal_sources
          );
          if (result) {
            const { name, datas } = result;
            if (name && datas) {
              try {
                const new_data = new PollingEntity();
                PollingEntity.copy(new_data, data);
                new_data.name = name;
                new_data.polling_signal_sources = datas;
                const resposne = await GlobalData.getInstance()
                  .getCurrentClient()
                  ?.editPolling(new_data);
                if (resposne) {
                  if (resposne.success) {
                    $q.notify({
                      color: "positive",
                      icon: "done",
                      message: $t.t("edit polling") + $t.t("success") + "!",
                      position: "top",
                      timeout: 1500,
                    });
                  } else {
                    $q.notify({
                      color: "negative",
                      icon: "warning",
                      message: $t.t("edit polling") + $t.t("failed") + "!",
                      position: "top",
                      timeout: 1500,
                    });
                  }
                }
              } catch (e) {
                console.log(e);
              }
            }
          }
        }
      },
      async addPolling(event: MouseEvent, data: any) {
        if (polling_setting_dialog.value) {
          const result = await polling_setting_dialog.value.showDialogAsync(
            null,
            []
          );
          if (result) {
            const { name, datas } = result;
            if (name && datas) {
              try {
                const resposne = await GlobalData.getInstance()
                  .getCurrentClient()
                  ?.addPolling(/* data.uuid */ "", name, datas);
                if (resposne) {
                  if (resposne.success) {
                    $q.notify({
                      color: "positive",
                      icon: "done",
                      message: $t.t("add polling") + $t.t("success") + "!",
                      position: "top",
                      timeout: 1500,
                    });
                  } else {
                    $q.notify({
                      color: "negative",
                      icon: "warning",
                      message: $t.t("add polling") + $t.t("failed") + "!",
                      position: "top",
                      timeout: 1500,
                    });
                  }
                }
              } catch (e) {
                console.log(e);
              }
            }
          }
        }
      },
      addPollingGroup(event: MouseEvent, data: any) {
        console.log(data);
      },
    };
  },
});
</script>
