
function formatDate(date = new Date()) {
    const year = date.toLocaleString('default', {year: 'numeric'});
    const month = date.toLocaleString('default', {
      month: '2-digit',
    });
    const day = date.toLocaleString('default', {day: '2-digit'});
  
    return [year, month, day].join('-');
}

function formatTime(date = new Date()) {
    const hour = ("0" + date.getHours()).slice(-2);
    const minutes = date.toLocaleString('default', {minute: '2-digit'});
  
    return [hour, minutes].join(':');
}

function isValidDate(d) {
    return d instanceof Date && !isNaN(d);
  }

const update_datetimes = (event) => {

    current = event.currentTarget;
    start_day = document.getElementById("id_start_day");
    end_day = document.getElementById("id_end_day");
    start_time = document.getElementById("id_start_time");
    end_time = document.getElementById("id_end_time");

    if (current == start_day) {
        if (end_day.value) {
            console.log("update day ", start_day.oldvalue, " -> ", start_day.value);
            
            new_date = new Date(start_day.value);
            old_date = new Date(start_day.oldvalue);

            end_date = new Date(end_day.value);
            end_date = new Date(end_date.getTime() + new_date.getTime() - old_date.getTime());
            if (isValidDate(end_date)) {
                end_day.value = formatDate(end_date);
            }

            start_day.oldvalue = start_day.value;
        }
        else {
            new_date = new Date(start_day.value);
            end_day.value = formatDate(new_date);
        }
    }
    else {
        if (end_day.value && end_time.value && start_day.value) {
            console.log("update time", start_time.oldvalue, " -> ", start_time.value);

            new_date = new Date(start_day.value + "T" + start_time.value);
            old_date = new Date(start_day.value + "T" + start_time.oldvalue);

            end_date = new Date(end_day.value + "T" + end_time.value);

            end_date = new Date(end_date.getTime() + new_date.getTime() - old_date.getTime());

            if (isValidDate(end_date)) {
                end_time.value = formatTime(end_date);
            }

            start_time.oldvalue = start_time.value;

        }
    }

};