<script setup lang="ts" >
import { useStore } from '@/store';
import { UABaseNode } from '@/ua/UABaseNode';
import { storeToRefs } from 'pinia';
import { ref, computed, watch } from 'vue'


const store = useStore()
const { selectedNode } = storeToRefs(store)


const props = defineProps<{
  model: UABaseNode,
  filterFunc?: Function,
  markSelected: Boolean
}>();

const emit = defineEmits(['selectNode']);

const isOpen = ref(false)
const selected = ref(false)
const isFolder = computed(() => {
  const children=props.model?.getChildren();
  return children && children.length;
})

const isFiltered = computed(() => {
  if(!props.filterFunc)
    return false;
  return props.filterFunc(props.model);
})

const children = computed(() => {
  return props.model.getChildren();
})

function toggle() {
  isOpen.value = !isOpen.value
}
function selectNode(node:UABaseNode) {
  emit('selectNode', node);
  //this hack avoids updating props and re-evaluating the whole tree on select
  //Needs ref to store unfortunately
  if(props.markSelected) {
    selected.value=true;
    const unwatch = watch(selectedNode, () => {
      selected.value=false;
      unwatch();
    });
  }
}
</script>

<template>
  <li>
    <div v-if="model"  :class="{ bold: isFolder }">
      <span v-if="isFolder" @click="toggle">[{{ isOpen ? '-' : '+' }}]</span>
      <span @click.stop="selectNode(model)"  class="itemtext" :class="[(isFiltered?'disabled':''), 
         selected?'selected':'' ]">
        {{ model.browseName }}
      </span>
    </div>
    <ul v-show="isOpen" v-if="isFolder && model">
        <TreeItem
          class="item"
          :filter-func = "$props.filterFunc"
          @select-node="(node: UABaseNode) => $emit('selectNode', node)"
          :markSelected="markSelected"
          v-for="child in children"
          v-bind:key="child.nodeId.toString()"
          :model="child">
        </TreeItem>
    </ul>
  </li>
</template>


<style scoped>
  body {
    font-family: Menlo, Consolas, monospace;
    color: #444;
  }
  .item {
    cursor: pointer;
    text-align: left;
    list-style-type: none;
  }
  .itemtext:hover{
    border: dashed 1px black;  
  }

  .selected{
    background-color: lightgrey;
  }

  .disabled {
    cursor: not-allowed;
    color: #aaa;
  }
  .bold {
    font-weight: bold;
  }
  ul {
    padding-left: 1em;
    line-height: 1.5em;
    list-style-type: dot;
  }
</style>