<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"
          />
          {{ trans(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-thirdparty
      v-if="type === 'thirdparty'"
      :action="action"
      :query="query"
      ref="castThirdparty"
    />
  </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";
import {
  trans,
  ONTHEFLY_CREATE_PERSON,
  ONTHEFLY_CREATE_THIRDPARTY,
} from "translator";

const props = defineProps({
  action: String,
  allowedTypes: Array,
  query: String,
});

const type = ref(null);

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

const castPerson = ref(null);
const castThirdparty = ref(null);

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

function isActive(tab) {
  return type.value === tab;
}

function castDataByType() {
  switch (radioType.value) {
    case "person":
      return castPerson.value.$data.person;
    case "thirdparty":
      let data = castThirdparty.value.$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");
  }
}

defineExpose({
  castDataByType,
});
</script>

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