<template>
  <div id="timeranges_s_e_container" class="flex justify-between items-center">
    <Durationjs :max="minVuemax" :min="minVuemin" :size="'min'" :updateMax="updateMax"
      @total-seconds="minTotalSeconds" :value="durationMin">
    </Durationjs>
      <span>~</span>
    <Durationjs :max="maxVuemax" :min="maxVuemin" :size="'max'" :updateMin="updateMin"
      @total-seconds="maxTotalSeconds" :value="durationMax">
    </Durationjs>
  </div>
</template>
<script setup>
import { ref, watch } from 'vue';
import Durationjs from '@/components/durationjs.vue';

const props = defineProps(['time', 'select']);
const emit = defineEmits(['min-total-seconds', 'max-total-seconds']);

const timeData = ref({ min: 0, max: 0 });
const timeRangeMin = ref(0);
const timeRangeMax = ref(0);
const minVuemin = ref(0);
const minVuemax = ref(0);
const maxVuemin = ref(0);
const maxVuemax = ref(0);
const updateMax = ref(null);
const updateMin = ref(null);
const durationMin = ref(null);
const durationMax = ref(null);

/**
 * set props values
 */
function setTimeValue() {
  // 深拷貝原始 timeData 的內容
  minVuemin.value = JSON.parse(JSON.stringify(timeData.value.min));
  minVuemax.value = JSON.parse(JSON.stringify(timeData.value.max));
  maxVuemin.value = JSON.parse(JSON.stringify(timeData.value.min));
  maxVuemax.value = JSON.parse(JSON.stringify(timeData.value.max));
}

/**
 * get min total seconds
 * @param {Number} e 元件傳來的最小值總秒數
 */
function minTotalSeconds(e) {
  timeRangeMin.value = e;
  updateMin.value = e;
  emit('min-total-seconds', e);
}

/**
 * get min total seconds
 * @param {Number} e 元件傳來的最大值總秒數
 */
function maxTotalSeconds(e) {
  timeRangeMax.value = e;
  updateMax.value = e;
  emit('max-total-seconds', e);
}

watch(() => props.time, (newValue, oldValue) => {
  durationMax.value = null;
  durationMin.value = null;
  if(newValue === null) {
    timeData.value = { min: 0, max: 0 };
  }else if(newValue !== null) {
    timeData.value = { min: newValue.min, max: newValue.max };
    emit('min-total-seconds', newValue.min);
    emit('max-total-seconds', newValue.max);
  }
  setTimeValue();
}, { deep: true, immediate: true });

// created
if(props.select){
  if(Object.keys(props.select.base).length !== 0) {
    timeData.value = props.select.base;
    setTimeValue();
  }
  if(Object.keys(props.select.rule).length !== 0) {
    durationMin.value = props.select.rule.min;
    durationMax.value = props.select.rule.max;
  }
}
</script>
