<template>
  <div >
    <div >
      <service-configuration-status-viewer :service-key="props.serviceKey" />
      <service-configuration-actions v-model:actionLog="actionLog" :service-key="props.serviceKey" />
    </div>
    <div  style="display: none;">
      <service-configuration-action-log :log="actionLog" />
    </div>
  </div>
</template>
<script setup>
import { ref, watch } from 'vue';
import ApiClient from '@/utils/ApiClient';
import ServiceConfigurationParamValueEdit from './ServiceConfigurationParamValueEdit.vue'
import ServiceConfigurationActionLog from './ServiceConfigurationActionLog.vue'
import ServiceConfigurationStatusViewer from './ServiceConfigurationStatusViewer.vue'
import ServiceConfigurationActions from './ServiceConfigurationActions.vue'
/** @var {Object} */
const props = defineProps({
  serviceKey: String,
});
/** @var {Array} */
const params = ref([]);
/** @var {Object} */
const actionLog = ref(null);
// watch service key
watch(() => props.serviceKey, handleServiceKeyChange);

// on mounted
async function handleServiceKeyChange() {
  if (null === props.serviceKey) {
    return;
  }

  await actionServiceParamReload();
}

// service param reload
async function actionServiceParamReload() {
  try {
    params.value = [];
    let client = ApiClient.getClient();
    let list = await client.call('service-config/service-params-list', { serviceKey: props.serviceKey });
    for (var item of list) {
      let groupName = item.group;
      let group = params.value.find(i => i.name === groupName);
      if (undefined === group) {
        group = { name: groupName, items: [], order: 0 };
        group.order = Math.max(group.order, item.order);
        params.value.push(group);
      }
      group.items.push(item);
    }
    params.value.map(g => g.items.sort((a, b) => a.order - b.order));
    params.value.sort((a, b) => a.order - b.order || b.items.length - a.items.length || b.name.localeCompare(a.name));
  } catch (e) {/** nothing to do here */ }
}


</script>