<script setup lang="ts">
import { useStore } from '@/util/store'
import { computed, ref } from 'vue';
import { UABaseNode } from '@/ua/UABaseNode';
import { ReferenceTypeIds } from '@/ua/opcua_node_ids';
import type { UAReferenceType } from '@/ua/UAReferenceType';
import { ObjectTypeIds } from '@/ua/opcua_node_ids';
import type { UAObjectType } from '@/ua/UAObjectType';
import { VariableTypeIds } from '@/ua/opcua_node_ids';
import type { UAVariableType } from '@/ua/UAVariableType';
import { UAReference } from '@/ua/UAReference';
import { UAObject } from '@/ua/UAObject';
import { UAVariable } from '@/ua/UAVariable';
import { DynamicNode, ComponentPair} 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 = {
  ident: "...",
  namespaceUri:"MyNamespace",
  parentNodeId: "MyNodeId",
  checkInterval:100,
  nodeClass:"Object",
  typeNodeId:"ns=0;i=88",
  name:"...",
  startIndex:0
};

let dynNode = new DynamicNode(opt);



function filter(fnode: UABaseNode) {
  if(selectedNode.value?.nodeClass==="Variable") {
    if(fnode.nodeClass!="Object")
      return true;
  }
  return false;
}

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(flag:any):UABaseNode[] {
    let list = [];
    if(flag){
        list=(store.addressSpace?.getSubTreeAsList("ns=0;i=89")||[]) as UAVariableType[]; 
    }else{
        list=(store.addressSpace?.getSubTreeAsList("ns=0;i=88")||[]) as UAObjectType[];
    }
  list=list.filter((node) => node.isAbstract==false)
  return list;
}

function defType(flag:any ):String{
    let lab = "ObjectType";
    if(flag){
        lab = "VariableType";
    }
    return lab;
}

function getInstanceDecl(nid="ns=0;i=84"){
  if(nid==""){nid="ns=0;i=84"}
  let component_refs:String[] = [];
  let res_man:any[] = [];
  let res_opt:any[] = [];
      dynNode.mandatory = [];
      dynNode.optionals = [];
  let res:any[] = [];
  let node =  (store.addressSpace?.findNode(nid)) as UABaseNode;
  let refs = node.references;
  let list = (store.addressSpace?.getSubTreeAsList("ns=0;i="+ReferenceTypeIds.Aggregates)||[]) as UABaseNode[];
  list.forEach((item) => {
    component_refs.push(item.browseName);
  })
  refs.forEach((item) => {
    if(component_refs.includes(item.referenceType) && item.isForward){
      let mr = "";
      if(item.toNode.nodeClass == "Object"){
        let i = item.toNode as UAObject;
        mr = i.getModellingRule()||"";
      }else if(item.toNode.nodeClass == "Variable"){
        let i = item.toNode as UAVariable;
        mr = i.getModellingRule()||"";
      }
      if(mr == "Mandatory"){
        const newItem = new ComponentPair(item.toNode.displayName , true);
        res_man.push(item.toNode.displayName);
      }else{
        const newItem = new ComponentPair(item.toNode.displayName , false);
        res_opt.push(item.toNode.displayName);
      }
      dynNode.mandatory = res_man;
      dynNode.optionals = res_opt;
      dynNode.o_check = new Array(res_opt.length).fill(false);
    }
  })
  return res;
}


function getComponents(nid:string):DynamicNode{
  getInstanceDecl(nid);
  return dynNode;
}

function getNodeVersion(nid:string, dynNode:DynamicNode){
  let node =  (store.addressSpace?.findNode(nid)) as UABaseNode;
  let refs = node.references;
  let res = "";
  refs.forEach((ref)=>{
    if(ref.toNode.displayName == "NodeVersion"){
      res= ref.toNode.nodeId.toString()
      dynNode.nodeVersionId= res;
      return res;
      
    }else if(ref.fromNode.displayName == "NodeVersion"){
      res= ref.fromNode.nodeId.toString()
      dynNode.nodeVersionId= res;
      return res;
    }
  })
  dynNode.nodeVersionId= res;
  return res;
}



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

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

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



}







const checked = ref("")
const c_man = ref([])
const c_opt = ref([])
const typedef = ref("")








</script>

<template>
  <div class="card">
    <div class="card-body" v-if="selectedNode != null && dynNode != 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" v-bind:key="'...'"> 
        </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" v-bind:key="1000"> 
        </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(), dynNode)" 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.displayName }}
            </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" v-bind:key="'...'"> 
        </div>
        <div class="input-group mb-3">
          <div class="input-group-prepend">
            <input type="checkbox" id="checkbox" v-model="checked" />
            <label for="checkbox">{{ defType(checked) }}</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(checked)" :value="option1.nodeId.toString()" v-bind:key="option1.nodeId.toString()">
              {{ option1.displayName }}
            </option>
          </select>
        </div>
        <div class="input-group mb-3">
          <ul class="no-bullets"><b>Mandatory Components</b>
            <li v-for="item of getComponents(typedef).mandatory">
              <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,index) of getComponents(typedef).optionals" :key="typedef">
              <input type="checkbox" id="checkbox-digg-{{ item1 }}" v-model="dynNode.o_check![index]" :value="item1" :checked="dynNode.o_check![index]">
              <label for="checkbox-digg-{{ item1 }}">{{ item1 }}</label>
            </li>
          </ul>
        </div>
        <div>
          <button class="btn btn-light" @click.prevent="createDynamic()">OK</button>
        </div>
      </div>
    </div>
  </div>
</template>


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