<script setup lang="ts">
import _ from 'lodash';
import { ref, onMounted } from 'vue';
import { computed } from 'vue';
import moment from 'moment';
import flatPickr from 'vue-flatpickr-component';
import 'flatpickr/dist/flatpickr.css';
import { German } from 'flatpickr/dist/l10n/de.js';
import rangePlugin from 'flatpickr/dist/plugins/rangePlugin.js';
import weekSelect from 'flatpickr/dist/plugins/weekSelect/weekSelect.js';

German.rangeSeparator ="~";//todo: move this src to main

const props = defineProps({ modelValue: { type: Object, required: true } });
const emit = defineEmits(['update:modelValue']);

const value = computed({
  get() {
    return props.modelValue;
  },
  set(val) {
    emit('update:modelValue', value.value);
  },
});

const config = ref({
    //altInput: true,
     //altFormat: "GGGG[W]WW",
     //allowInput: true,
    mode: "range",
  wrap: true, // set wrap to true only when using 'input-group'
  dateFormat: 'GGGG[W]WW',//'Y-m-d'
  defaultDate: value.data,
  locale: German, // locale for this instance only
  //plugins: [new weekSelect({})],
  weekNumbers: true,
  //showMonths:2,
  /*getWeek: function (dateObj) {
    const current = moment(dateObj).startOf('isoWeek');    
    return `${current.isoWeekYear()}W${current.isoWeek().toString().padStart(2, '0')}`;
  },*/
  parseDate: (datestr, format) => {
    console.log('parseDate',datestr, format);
    return moment(datestr, format, true).toDate();
  },
  formatDate: (date, format, locale) => {
    //console.log('formatDate',date, format, locale);
    //const current = moment(date).startOf('isoWeek');    
    //return `${current.isoWeekYear()}W${current.isoWeek().toString().padStart(2, '0')}`;
    return moment(date).format(format);
  },
  onReady: function () {
    console.log('end week', value.value);
  },
});

onMounted(() => {
  console.log('   onMounted     ', props.modelValue); // don't use this keyword
});
</script>

<template>
  <div class="week-selector">
    <div class="form-group">
      <flat-pickr v-model="value.data" :config="config" class="form-control" placeholder="Select week1" name="date" />
    </div>   
  </div>
</template>

<style scoped>
.select-input {
  padding: 0.5rem;
  border: 1px solid #ccc;
  border-radius: 4px;
  width: 200px;
}
</style>
