import { formats } from './formats';
import { newDate } from './date-utils';

export const isValidEpoch = (val) => !Number.isNaN(Number(val));

export const isNumber = (val) => !!String(val || '').trim() && !Number.isNaN(Number(val));

export const getPartsFromEpoch = (epoch) => {
  const date = newDate(epoch);
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  return [year, month, day];
};

export const formatEpoch = (epoch, format) => {
  const [year, month, day] = getPartsFromEpoch(epoch);

  const parts = {
    DD: String(day).padStart(2, '0'),
    MM: String(month).padStart(2, '0'),
    YYYY: String(year),
  };

  return format.replace(/DD|MM|YYYY/g, (match) => parts[match]);
};

export const getCurrentTime = () => newDate().getTime();
export const getFullYear = (epoch) => newDate(epoch).getFullYear().toString();
export const getMonth = (epoch) => (newDate(epoch).getMonth() + 1).toString();
export const getCurrentDay = () => newDate().getDate();
export const getCurrentYear = () => newDate().getFullYear().toString();

// Vaadin uses "constructed stylesheet" to hide the host in dialog components.
// To override it, we need to push an overriding constructed stylesheet to the shadow DOM
// opened issue in vaadin: https://github.com/vaadin/web-components/issues/7979
export const overrideConstructedStylesheet = (ele) => {
  const cs = new CSSStyleSheet();
  cs.insertRule(':host{display:block!important;}');
  ele?.shadowRoot?.adoptedStyleSheets?.push(cs);
};

export const parseDateString = (val, format) => {
  const trimmed = val.trim?.();
  if (!trimmed) return null;
  return formats[format].getDate(trimmed);
};

export const dateToEpoch = (date, isUtc) => {
  // If it's already a number (epoch), return it directly - no conversion needed
  if (typeof date === 'number') {
    return date;
  }

  if (isUtc) {
    return Date.UTC(date.getFullYear(), date.getMonth(), date.getDate());
  }

  // Default: return epoch in local timezone
  return date.getTime();
};
