<template>
   <ul class="nav nav-tabs">
      <li v-if="allowedTypes.includes('person')" class="nav-item">
         <a class="nav-link" :class="{ active: isActive('person') }">
            <label for="person">
               <input type="radio" name="person" id="person" v-model="radioType" value="person">
               {{ $trans('ONTHEFLY_CREATE_PERSON') }}
            </label>
         </a>
      </li>
      <li v-if="allowedTypes.includes('thirdparty')" class="nav-item">
         <a class="nav-link" :class="{ active: isActive('thirdparty') }">
            <label for="thirdparty">
               <input type="radio" name="thirdparty" id="thirdparty" v-model="radioType" value="thirdparty">
               {{ $t('onthefly.create.thirdparty') }}
            </label>
         </a>
      </li>
   </ul>

   <div class="my-4">
      <on-the-fly-person
         v-if="type === 'person'"
         :action="action"
         :query="query"
         ref="castPerson"
      >
      </on-the-fly-person>

      <on-the-fly-thirdparty
         v-if="type === 'thirdparty'"
         :action="action"
         :query="query"
         ref="castThirdparty"
      >
      </on-the-fly-thirdparty>
   </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import OnTheFlyPerson from 'ChillPersonAssets/vuejs/_components/OnTheFly/Person.vue';
import OnTheFlyThirdparty from 'ChillThirdPartyAssets/vuejs/_components/OnTheFly/ThirdParty.vue';

// Define props
const props = defineProps(['action', 'allowedTypes', 'query']);

// Create a ref for type
const type = ref(null);

// Computed
const radioType = computed({
    get: () => type.value,
    set(value) {
        type.value = value;
        console.log('## type:', value, ', action:', props.action);
    }
});

// Mounted
onMounted(() => {
    type.value = (props.allowedTypes.length === 1 && props.allowedTypes.includes('thirdparty'))
        ? 'thirdparty'
        : 'person';
});

// Methods
const isActive = (tab) => {
    return type.value === tab;
};

const castDataByType = () => {
    switch (radioType.value) {
        case 'person':
            return $refs.castPerson.$data.person;
        case 'thirdparty':
            let data = $refs.castThirdparty.$data.thirdparty;
            if (data.address !== undefined && data.address !== null) {
                data.address = { id: data.address.address_id };
            } else {
                data.address = null;
            }
            return data;
        default:
            throw Error('Invalid type of entity');
    }
};

// Register components
defineExpose({
    isActive,
    castDataByType
});

</script>

<style lang="css" scoped>
label {
   cursor: pointer;
}
</style>
