<template>
  <q-input
    class="col-xs-12 col-sm-6 q-pa-sm"
    filled
    :readonly="readonly"
    :label="label"
    :value="getDate()"
    placeholder="YYYY-MM-DD"
    v-on:input="dateChanged"
    :rules="[isDate]"
  >
    <template v-slot:append>
      <q-icon
        name="event"
        class="cursor-pointer"
      >
        <q-popup-proxy
          ref="qDateProxy"
          transition-show="scale"
          transition-hide="scale"
        >
          <q-date
            :value="getDate()"
            mask="YYYY-MM-DD"
            v-on:input="dateChanged"
          >
            <div class="row items-center justify-end">
              <q-btn
                v-close-popup
                label="Schließen"
                color="primary"
                flat
              />
            </div>
          </q-date>
        </q-popup-proxy>
      </q-icon>
    </template>
  </q-input>
</template>

<script lang="ts">
import { defineComponent } from '@vue/composition-api';
import { date } from 'quasar';
interface Props {
  value?: Date;
  label?: string;
  readonly: boolean;
}

export default defineComponent({
  name: 'IsoDateInput',
  props: {
    value: {
      required: true,
    },
    label: {},
    readonly: {
      default: false,
    },
  },
  setup(props: Props, { emit }) {
    function getDate() {
      if (props.value) {
        return date.formatDate(props.value, 'YYYY-MM-DD');
      }
      return '';
    }

    function dateChanged(dateString: string) {
      emit('input', new Date(dateString));
    }

    function isDate(val: string) {
      return !val || /^\d{4}-\d\d-\d\d$/.test(val) || 'Datum ist nicht gültig.';
    }

    return {
      getDate,
      dateChanged,
      isDate,
    };
  },
});
</script>
