/*!
 * Copyright (c) 2022 Eclipse Foundation, Inc.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v. 2.0 which is available at
 * http://www.eclipse.org/legal/epl-2.0.
 *
 * Contributors:
 *   Zhou Fang <zhou.fang@eclipse-foundation.org>
 *
 * SPDX-License-Identifier: EPL-2.0
 */

const convertTimeIntoLocale = (() => {
  const originalTimes = document.querySelectorAll('.dynamic-time');

  originalTimes.forEach((originalTime) => {
    // Separate the time if there is a dash between them
    const timeValues = originalTime.textContent.replaceAll(' ', '').split('-');

    // check if data-tz is available, if not, use "GMT-04" as default
    const originalTimezone = originalTime.getAttribute('data-tz') || 'GMT-04';
    const startTime = timeValues[0];

    // Use '' for endTime if there is only 1 time value in the array
    const endTime = timeValues[1] || '';

    // As date won't impact the time conversion, so use today to create date object
    const date = new Date().toDateString();
    const startTimeInCurrentTZ = new Date(`${date} ${startTime} ${originalTimezone}`);
    const endTimeInCurrentTZ = new Date(`${date} ${endTime} ${originalTimezone}`);

    // Get the time value from date string in HH:MM format
    const getTime = (date) => date.toString().slice(16, 21);

    // Will not show endTime if it doesn't exist
    originalTime.textContent = endTime
      ? `${getTime(startTimeInCurrentTZ)}-${getTime(endTimeInCurrentTZ)} ${endTimeInCurrentTZ.toString().slice(25, 31)}`
      : `${getTime(startTimeInCurrentTZ)} ${startTimeInCurrentTZ.toString().slice(25, 31)}`;
  });
})();
