<template>
  <div>
    <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)"
        >
          <q-item-section avatar>
            <q-icon
              :name="
                prop.node.is_group
                  ? 'img:source_icon/group.png'
                  : getItemIcon(prop.node.item_data?.window_type)
              "
              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-popup-proxy context-menu />
            <q-list>
              <q-item
                v-if="
                  prop.node.name == $t('root') ||
                  (prop.node.is_group &&
                    prop.node.item_data &&
                    !prop.node.item_data.system_default)
                "
                clickable
                v-close-popup
                v-ripple
                @click="
                  $refs.signal_source_dialog.showDialog({
                    type: 1,
                    parent_node: prop.node.uuid,
                  })
                "
              >
                <q-item-section avatar><q-icon name="add" /></q-item-section>
                <q-item-section>{{
                  $t("add signal source item")
                }}</q-item-section>
              </q-item>
              <q-item
                clickable
                v-close-popup
                v-if="
                  prop.node.name == $t('root') ||
                  (prop.node.is_group &&
                    prop.node.item_data &&
                    !prop.node.item_data.system_default)
                "
                v-ripple
                @click="
                  () =>
                    $refs.group_dialog.showDialog({
                      type: 1,
                      data: prop.node,
                    })
                "
              >
                <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.item_data && !prop.node.item_data.system_default
                "
                @click="
                  () =>
                    (prop.node.is_group
                      ? $refs.group_dialog
                      : $refs.signal_source_dialog
                    ).showDialog({
                      type: 2,
                      data: prop.node,
                    })
                "
              >
                <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 && !prop.node.item_data.system_default
                "
                @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>
  </div>
  <group-dialog ref="group_dialog" />
  <signal-source-dialog ref="signal_source_dialog" />
</template>

<script lang="ts">
import { defineComponent, computed, onMounted, ref, nextTick } from "vue";
import { useStore } from "src/store";
import { SignalSourceTreeItemEntity } from "src/entities/SignalSourceEntity";
import GroupDialog from "src/components/GroupDialog.vue";
import SignalSourceDialog from "src/components/SignalSourceDialog.vue";
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";

export default defineComponent({
  name: "PageLeftToolBar",

  components: { GroupDialog, SignalSourceDialog },

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

    const tree_nodes = computed({
      get: () => $store.state.signal_source_tree,
      set: (val) => $store.commit("setSignalSourceTree", val),
    });

    const tree: any | null = ref(null);

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

    interface _ResponseMessage {
      packet: Protocol.PacketEntity;
      data: string;
    }
    EventBus.getInstance().on(
      EventNamesDefine.NotifyMessage,
      (response: _ResponseMessage) => {
        if (response) {
          switch (response.packet.command) {
            case Protocol.Commands.kRpcAddSignalSource:
              {
                const temp = JSON.parse(
                  response.data
                ) as Protocol.SignalSourceAddNotifyEntity;
                if (temp) {
                  GlobalData.getInstance().signal_source.push(
                    temp.signal_source
                  );
                  $store.commit("addSignalSourceTreeItem", {
                    parent: temp.signal_source.group_uuid,
                    is_group: false,
                    item_data: temp.signal_source,
                  });
                }
              }
              break;
            case Protocol.Commands.kRpcDeleteSignalSource:
              {
                const temp = JSON.parse(
                  response.data
                ) as Protocol.SignalSourceDeleteNotifyEntity;
                if (temp) {
                  $store.commit("deleteSignalSourceTreeItem", {
                    is_group: false,
                    uuid: temp.uuid,
                  });
                }
              }
              break;
            case Protocol.Commands.kRpcEditSignalSource:
              {
                const temp = JSON.parse(
                  response.data
                ) as Protocol.SignalSourceEditNotifyEntity;
                if (temp) {
                  $store.commit("setSignalSourceTreeItem", {
                    is_group: false,
                    item_data: temp.signal_source,
                  });
                }
              }
              break;
            case Protocol.Commands.kRpcAddSignalSourceGroup:
              {
                const temp = JSON.parse(
                  response.data
                ) as Protocol.SignalSourceGroupAddNotifyEntity;
                if (temp) {
                  $store.commit("addSignalSourceTreeItem", {
                    parent: temp.signal_source_group.parent_uuid,
                    is_group: true,
                    item_data: temp.signal_source_group,
                  });
                }
              }
              break;
            case Protocol.Commands.kRpcDeleteSignalSourceGroup:
              {
                const temp = JSON.parse(
                  response.data
                ) as Protocol.SignalSourceGroupDeleteNotifyEntity;
                if (temp) {
                  $store.commit("deleteSignalSourceTreeItem", {
                    is_group: true,
                    uuid: temp.uuid,
                  });
                }
              }
              break;
            case Protocol.Commands.kRpcEditSignalSourceGroup:
              {
                const temp = JSON.parse(
                  response.data
                ) as Protocol.SignalSourceGroupEditNotifyEntity;
                if (temp) {
                  $store.commit("setSignalSourceTreeItem", {
                    is_group: true,
                    item_data: temp.signal_source_group,
                  });
                }
              }
              break;
          }
        }
      }
    );

    return {
      tree,
      tree_nodes,
      loga(a: any) {
        console.log(a);
      },
      onDragStart(e: DragEvent, node: SignalSourceTreeItemEntity) {
        e.dataTransfer?.setData("uuid", node.uuid);
        e.dataTransfer?.setData("node_object", JSON.stringify(node));
        if (e.dataTransfer) {
          e.dataTransfer.dropEffect = "move";
        }
      },
      getItemIcon(item_type: string) {
        return Common.getSignalSourceIcon(item_type);
      },
      async deleteItem(
        evt: PointerEvent | null,
        is_group: boolean,
        uuid: string
      ) {
        let success = false;
        if (is_group) {
          let response = await GlobalData.getInstance()
            .getCurrentClient()
            ?.deleteSignalSourceGroup(uuid);
          if (response) {
            success = response.success;
          }
        } else {
          let response = await GlobalData.getInstance()
            .getCurrentClient()
            ?.deleteSignalSource(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: 1000,
        });
      },
    };
  },
});
</script>
