<template>
    <Head>
        <title>RPO TISK</title>
    </Head>
    <Layout>
        <q-page class="column flex-center">
            <div class="flex q-gutter-lg justify-center items-center">
                <JsonQueryBuilder :query="query" :queryOptions="rpoMultiselect" @run-query="submit" ></JsonQueryBuilder>
            </div>

            <div class="q-mt-xl">
             {{ query }}
            </div>

        </q-page>
    </Layout>
</template>

<script setup>
import Layout from "../layouts/MainLayout.vue";
import JsonQueryBuilder from '../components/JsonQueryBuilder.vue';
import { ref, watch, computed } from "vue";
import { Head } from "@inertiajs/vue3";
import { router } from '@inertiajs/vue3';
import { Dark } from "quasar";
import rpoJsonData from '../Data/RpoTree.json';

const query = ref({
        condition: 'and',
        rules: [{
          id: 'addresses.municipality.value',
          operator: '=',
          value: 'Bratislava'
          }, {
          condition: 'or',
          rules: [{
            id: 'statutoryBodies.personName.familyNames',
            operator: '=',
            value: 'Grochalová'
          }, {
            id: 'statutoryBodies.personName.familyNames',
            operator: '=',
            value: 'Grochal'
          }]
        }]
      })

console.log('QUERY',query);

const submit = () => {
    console.log('Post data');
    console.log(query.value);
    router.post(`/search`, query.value);
};

function createRPOmulti(tree,flatListRpo, level = 0, fullPathRpo = []) {
    console.log('keys=',Object.keys(tree));
    console.log('TT=',typeof tree);
    let fullPath = [ ...fullPathRpo ] ;
    if (tree.desc != undefined) fullPath.push(tree.desc);

    if (level == 0 || tree.type == "Object" || tree.type == "Array" || tree.type == undefined) {
      Object.keys(tree).forEach(k => {
        console.log('k=',k);
        console.log('obj=',tree[k]);
        console.log(typeof tree[k]);
        console.log('t=',tree[k].type);
        console.log('rec=',k);
        if (typeof tree[k] != 'string') {
          console.log('DESC=',tree[k].desc);
          createRPOmulti(tree[k], flatListRpo, level + 1, fullPath );
        }
      });
  } else {
          flatListRpo.push({"name":tree.name, "type": tree.type, "desc": fullPath.join(' → ') });
  }
}

const rpoMultiselect = computed(() => {
    console.log('Rpo Multiselect');
    var flatList = [];
    createRPOmulti(rpoJsonData, flatList);
    return flatList;
});





const count = ref(0);
const min = -5;
const max = 5;

const darkMode = ref(Dark.isActive);
watch(darkMode, (value) => {
    Dark.set(value);
});
</script>
