<script setup>
import { useHead, useLight } from "#imports";
import { useRouter, useRoute } from "vue-router";
import model from "../../composables/model";
import getID from "../../composables/getID";
import { computed } from "vue";
const router = useRouter();
const route = useRoute();
const light = useLight();
const props = defineProps({
  padding: { type: Boolean, required: false, default: true },
  styleFn: { type: Function, required: false, skipCheck: true },
  title: { type: String, required: false, default: "" },
  backBtn: { type: Boolean, required: false, default: true },
  editBtn: { type: Boolean, required: false },
  deleteBtn: { type: Boolean, required: false },
  addBtn: { type: Boolean, required: false },
  gutter: { type: String, required: false, default: "sm" },
  breadcrumbs: { type: Boolean, required: false }
});
const showToolbar = computed(
  () => !!(props.backBtn || props.editBtn || props.deleteBtn || props.addBtn)
);
const title = computed(() => {
  let t = props.title || route.path.split("/")[1].replace(/([a-z])(?=[A-Z])/g, "$1 ").replace(/([A-Z]*)(?=[A-Z][a-z])/g, "$1 ");
  t = t.replace(/\s\s+/g, " ");
  t = t.trim();
  return t;
});
const module = route.path.split("/")[1];
const onDelete = async () => {
  const id = getID();
  if (id) {
    if (await model(module).delete(id)) {
      router.push(`/${module}`);
    }
  }
};
useHead({
  title: () => light.company + " - " + title.value
});
const localClass = computed(() => {
  return "q-gutter-" + props.gutter;
});
const lastPart = computed(() => {
  const parts = route.path.split("/").filter((part2) => isNaN(Number(part2)));
  if (parts.length < 2) {
    return false;
  }
  let part = parts[parts.length - 1];
  if (!part) {
    return false;
  }
  part = part.replace(/_/g, " ").replace(/([a-z])(?=[A-Z])/g, "$1 ").replace(/([A-Z]*)(?=[A-Z][a-z])/g, "$1 ");
  part = part.replace(/\b\w/g, (char) => char.toUpperCase());
  part = part.replace(/\s\s+/g, " ").trim();
  return part;
});
</script>

<template>
    <q-page :padding="padding" class="q-pt-sm">
        <q-toolbar v-if="showToolbar">
            <l-back-btn v-if="backBtn" dense />
            <l-add-btn v-if="addBtn" dense />
            <l-edit-btn v-if="editBtn" dense />
            <l-delete-btn v-if="deleteBtn" @submit="onDelete" dense />
            <q-toolbar-title>{{ $t(title) }}</q-toolbar-title>
            <q-breadcrumbs v-if="breadcrumbs">
                <q-breadcrumbs-el :label="$t('Home')" to="/" icon="home" />
                <q-breadcrumbs-el :label="$t(title)" :to="'/' + route.path.split('/')[1]"
                    v-if="route.path.split('/')[1]" />
                <q-breadcrumbs-el v-if="lastPart" :label="lastPart" :to="route.fullPath" />
            </q-breadcrumbs>
        </q-toolbar>

        <div :class="localClass">
            <slot name="header"></slot>
            <slot></slot>
        </div>

    </q-page>
</template>
