<script setup>
import { computed, watch, reactive } from "vue";
const model = defineModel({
  type: String,
  default: ""
});
const props = defineProps({
  type: {
    type: String,
    default: "text"
  }
});
const isRequired = computed(() => {
  return model.value.split("|").includes("required");
});
const isEmail = computed(() => {
  return model.value.split("|").includes("email");
});
const isNumber = computed(() => {
  return model.value.split("|").includes("number");
});
const lenghtMin = computed(() => {
  const length = model.value.split("|").find((v) => v.includes("length"));
  if (length) {
    return length.split(":")[1].split(",")[0];
  }
  return 0;
});
const lenghtMax = computed(() => {
  const length = model.value.split("|").find((v) => v.includes("length"));
  if (length) {
    return length.split(":")[1].split(",")[1];
  }
  return 0;
});
const form = reactive({
  required: isRequired.value,
  email: isEmail.value,
  number: isNumber.value,
  length_min: lenghtMin.value,
  length_max: lenghtMax.value
});
watch(form, () => {
  let validation = [];
  if (form.required) {
    validation.push("required");
  }
  if (props.type == "text") {
    if (form.email) {
      validation.push("email");
    }
    if (form.number) {
      validation.push("number");
    }
    if (form.length_min > 0 || form.length_max > 0) {
      if (form.length_max > 0) {
        validation.push(`length:${form.length_min},${form.length_max}`);
      } else {
        validation.push(`length:${form.length_min}`);
      }
    }
  }
  model.value = validation.join("|");
});
</script>

<template>
    <q-checkbox left-label v-model="form.required" label="Required" />

    <q-checkbox left-label v-model="form.email" label="Email" v-if="type == 'text'" />

    <q-checkbox left-label v-model="form.number" label="Number" v-if="type == 'text'" />

    <l-row v-if="type = 'text'">
        <l-col :md="6">
            <q-input label="Length min" v-model="form.length_min" type="number" stack-label outlined dense :min="0" />
        </l-col>
        <l-col :md="6">
            <q-input label="Length max" v-model="form.length_max" type="number" stack-label outlined dense :min="0" />
        </l-col>
    </l-row>
</template>
