<script setup lang="ts">
import { useStore } from '@/store'
import { computed, ref, watch } from 'vue';
import { UABaseNode } from '@/ua/UABaseNode';
import { ObjectIds, ReferenceTypeIds } from '@/ua/opcua_node_ids';
import type { UAReferenceType } from '@/ua/UAReferenceType';
import type { UAVariableType } from '@/ua/UAVariableType';
import { type DynamicNodeData} from '@/ua/DynamicNode';
import { storeToRefs } from 'pinia';
const store = useStore();
const { selectedNode} = storeToRefs(store)

const nameSpaceName = computed(() => {
  if(!selectedNode.value)
    return "";
  let nsIdx=selectedNode.value.nodeId.namespace;
  return store.addressSpace?.nst.getUri(nsIdx);
})

let opt: DynamicNodeData = {
  ident: "...",
  namespaceUri:"MyNamespace",
  parentNodeId: "MyNodeId",
  checkInterval:100,
  nodeClass:"Object",
  typeNodeId:"ns=0;i=88",
  name:"...",
  startIndex:0
};
const dynNode = ref(opt);
const checked = ref("")
const typedef = ref("")

watch(selectedNode, async (newNode, _oldNode) => {
  if(!newNode)
    return;
  let dynConfig=store.serverConfig.configData.dynamics?.find((d) => {d.parentNodeId==newNode.nodeId.toString()})||{}
  dynNode.value=dynConfig;
  //TODO: what id does/should typedef hold?
  typedef.value=newNode.nodeId.toString();
})

function getRefTypes():UABaseNode[] {
  let list=(store.addressSpace?.getSubTreeAsList("ns=0;i="+ReferenceTypeIds.HierarchicalReferences)||[]) as UAReferenceType[];
  list=list.filter((node) => node.isAbstract==false)
  return list;
}

function getObjTypes(nid: string):UABaseNode[] {
  const list=(store.addressSpace?.getSubTreeAsList(nid)||[]) as UAVariableType[]; 
  return list.filter((node) => node.isAbstract==false)
}

function getInstanceDecl(nid: string, mrType: string){
  const aggregates = (store.addressSpace?.getSubTreeAsList("ns=0;i="+ReferenceTypeIds.Aggregates)||[]) as UABaseNode[];
  let aggStrings:String[] = [];
  aggregates.forEach((item) => {
    aggStrings.push(item.browseName);
  })
  let node =  (store.addressSpace?.findNode(nid)) as UABaseNode;
  let res:string[] = [];
  node.references.forEach((item) => {
    if(aggStrings.includes(item.referenceType) && item.isForward){
      let mr = item.toNode.getModellingRule()||"";
      if(mr == mrType){
        res.push(item.toNode.browseName||"");
      }
    }
  })
  return res;
}

function getNodeVersion(nid:string){
  let node =  (store.addressSpace?.findNode(nid)) as UABaseNode;
  if(!node) 
    return "";
  let refs = node.references;
  refs.forEach((ref)=>{
    if(ref.toNode.browseName == "NodeVersion" && ref.isForward){
      return ref.toNode.nodeId.toString()      
    }else if(ref.fromNode.browseName == "NodeVersion" && !ref.isForward){
      return ref.fromNode.nodeId.toString()
    }
  })
}

async function createDynamic() {
  //dynNode.namespaceUri = nameSpaceName.value;
  //dynNode.parentNodeId = selectedNode.value?.nodeId.toString();
  // dynNode.value.typeNodeId = typedef.value.toString();

 // console.log(dynNode);
  //console.log(c_man);
  //console.log(c_opt.value);
  // console.log(dynNode.value.dynamicNodeData.optionals)
  // console.log(dynNode.value.o_check)
  //dynNode = new DynamicNode(opt);

  /*
  const blob = await store.addressSpace?.exportProject();
  if ('dynamics' in sconfig){
    sconfig.dynamics.push("hello");
  }else{
    sconfig.dynamics = [];
  }
   */



}


function okPressed() {
  store.serverConfig.addDynamic(dynNode.value);
}
defineExpose({ okPressed })
</script>

<template>
  <div class="card">
    <div class="card-body" v-if="selectedNode != null">
      <h5 class="card-title">Dynamic Node</h5>
      <div class="card-text">
        <div class="input-group mb-3">
          <div class="input-group-prepend">
            <span class="input-group-text" id="inputGroup-sizing-default">Parent Node</span>
          </div>
          <input type="text" class="form-control" aria-label="Default"
            aria-describedby="inputGroup-sizing-default" v-model="selectedNode.nodeId" disabled> 
        </div>
        <div class="input-group mb-3">
          <div class="input-group-prepend">
            <span class="input-group-text" id="inputGroup-sizing-default">Namespace</span>
            </div>
            <input type="text" class="form-control" aria-label="Default" aria-describedby="inputGroup-sizing-default" v-model="nameSpaceName" disabled>
        </div>
        <div class="input-group mb-3">
          <div class="input-group-prepend">
            <span class="input-group-text" id="inputGroup-sizing-default">Name Dynamic Definition</span>
          </div>
          <input type="text" class="form-control" aria-label="Default"
            aria-describedby="inputGroup-sizing-default" v-model="dynNode.name"> 
        </div>
        <div class="input-group mb-3">
          <div class="input-group-prepend">
            <span class="input-group-text" id="inputGroup-sizing-default">Update Interval in ms</span>
          </div>
          <input type="text" class="form-control" aria-label="Default"
            aria-describedby="inputGroup-sizing-default" v-model="dynNode.checkInterval"> 
        </div>
        <div class="input-group mb-3">
          <div class="input-group-prepend">
            <span class="input-group-text" id="inputGroup-sizing-default">NodeVersion</span>
          </div>
          <input type="text" class="form-control" aria-label="Default"
            aria-describedby="inputGroup-sizing-default" :value="getNodeVersion(selectedNode.nodeId.toString())" disabled> 
        </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="Default select example">
            <option v-for="option in getRefTypes()" :value="option.nodeId.toString()" v-bind:key="option.nodeId.toString()">
              {{ option.browseName }}
            </option>
          </select>
        </div>
        <div class="input-group mb-3">
          <div class="input-group-prepend">
            <span class="input-group-text" id="inputGroup-sizing-default">Ident</span>
          </div>
          <input type="text" class="form-control" aria-label="Default"
            aria-describedby="inputGroup-sizing-default" v-model="dynNode.ident"> 
        </div>
        <div class="input-group mb-3">
          <div class="input-group-prepend">
            <input type="checkbox" id="checkbox" v-model="checked" />
            <label for="checkbox">{{ checked?"ObjectType":"VariableType" }}</label>
          </div>
        </div>
        <div class="input-group mb-3">
          <div class="input-group-prepend">
            <span class="input-group-text" id="inputGroup-sizing-default">Type Definition</span>
          </div>
          <select v-model="typedef" class="form-select" aria-label="Default select example" >
            <option v-for="option1 in getObjTypes('ns=0;i='+ ObjectIds.VariableTypesFolder)" :value="option1.nodeId.toString()" v-bind:key="option1.nodeId.toString()">
              {{ option1.browseName }}
            </option>
          </select>
        </div>
        <div class="input-group mb-3">
          <ul class="no-bullets"><b>Mandatory Components</b>
            <li v-for="item of getInstanceDecl(typedef, 'Mandatory')" v-bind:key = item>
              <input type="checkbox" id="checkbox-digg-{{ item }}" :checked="true" :disabled="true">
              <label for="checkbox-digg-{{ item}}">{{ item}}</label>
            </li>
          </ul>
        </div>
        <div>
          <ul class="no-bullets"><b>Optional Components</b>
            <li v-for="(item1) of getInstanceDecl(typedef, 'Optional')" v-bind:key = item1>
              <input type="checkbox" id="checkbox-digg-{{ item1 }}"  :value="item1">
              <label for="checkbox-digg-{{ item1 }}">{{ item1 }}</label>
            </li>
          </ul>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
  ul.no-bullets {
  list-style-type: none;
  margin: 0;
  padding: 0;
}
</style>@/store