<script setup lang="ts">
import { useStore } from '@/store'
import { computed, ref, watch } from 'vue';
import TheTreeDialog from './TheTreeDialog.vue';
import VCollaps from './VCollaps.vue';
import { UABaseNode } from '@/ua/UABaseNode';
import { ReferenceTypeIds } from '@/ua/opcua_node_ids';
import type { UAReferenceType } from '@/ua/UAReferenceType';
import { storeToRefs } from 'pinia';
const store = useStore()
const parentDialogOpen = ref(false);
const { selectedNode } = storeToRefs(store)
const selectedRefType = ref('')
const selectedParent = ref(UABaseNode.nullBaseNode);
let dirty = false;

function clickNode(clickedNode: UABaseNode) {
  selectedParent.value=clickedNode;
  parentDialogOpen.value=false;
}

watch(selectedNode, async (newNode, _oldNode) => {
  selectedRefType.value=newNode?.getParentRef()?.referenceType||"";
  selectedParent.value=newNode?.getParent()||UABaseNode.nullBaseNode;
  dirty=false;
})

function formChanged(){
  dirty=true;
}

function okPressed() {
  if(!dirty)
    return;
  //TODO: check if valid
  selectedNode.value?.setParent(selectedParent.value, selectedRefType.value);
}
defineExpose({ okPressed })

function filter(fnode: UABaseNode) {
  if(selectedNode.value?.nodeClass==="Variable") {
    if(fnode.nodeClass!="Object")
      return true;
  }
  return false;
}
const refTypes = computed(():UABaseNode[]  => {
  const list=(store.addressSpace?.getSubTreeAsList("ns=0;i="+ReferenceTypeIds.HierarchicalReferences)) as UAReferenceType[];
  return list.filter((node) => node.isAbstract==false);
})
</script>

<template>
  <VCollaps :selected=false name="Parent" @change="formChanged()">
    <div class="card-text"  v-if="selectedNode">
      <div class="input-group mb-3">
        <div class="input-group-prepend">
          <span class="input-group-text" id="inputGroup-sizing-default">Name</span>
        </div>
        <input readonly type="text" class="form-control" aria-label="Default"
          aria-describedby="inputGroup-sizing-default" :value="selectedParent.browseName">
          <button class="btn btn-light" @click="parentDialogOpen = true">...</button>
      </div>
      <div class="input-group mb-3">
        <div class="input-group-prepend">
          <span class="input-group-text" id="inputGroup-sizing-default">Reference</span>
        </div>
        <select class="form-select" aria-label="Selected ref. type" v-model="selectedRefType" >
          <option v-for="option in refTypes" :value="option.browseName" v-bind:key="option.browseName">
            {{ option.browseName }}
          </option>
        </select>
      </div>
    </div>
  </VCollaps>
  <TheTreeDialog 
    :open="parentDialogOpen" 
    :filter-func="(node: UABaseNode) => filter(node)"
    @cancel="parentDialogOpen = false" 
    :markSelected="false"
    @select-node="(node) => clickNode(node)">
  </TheTreeDialog>
</template>


<style scoped></style>