import { Alert } from '@suid/material';
import { Component, createSignal, onCleanup, Show } from 'solid-js';

interface Props {}

const Updater: Component<Props> = (props) => {
  const [updateNeeded, setUpdateNeeded] = createSignal(false);

  const checkUpdate = async () => {
    const response = await fetch(
      'https://dyomedea.app/assets/release/dyomedea.rel',
      {
        mode: 'cors', // no-cors, *cors, same-origin
        cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
        credentials: 'same-origin',
      }
    );
    const latestRelease = (await response.text()).replace('\n', '');
    const currentRelease = import.meta.env.VITE_GIT_COMMIT_HASH;
    console.log({ caller: 'checkUpdate', currentRelease, latestRelease });
    setUpdateNeeded(latestRelease !== currentRelease);
  };

  const intervalId = setInterval(checkUpdate, 30 * 1000);

  onCleanup(() => {
    clearInterval(intervalId);
  });

  return (
    <Show when={updateNeeded()}>
      <Alert severity='warning'>
        Please reload this page to update the application.
      </Alert>
    </Show>
  );
};

export default Updater;
