import { Alert, Button } from '@suid/material';
import { Component, createSignal, onCleanup, Show } from 'solid-js';
import { Browser } from '@capacitor/browser';
import style from './Updater.module.css';

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, 60 * 60 * 1000);

  checkUpdate();

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

  return (
    <>
      <Show when={updateNeeded()}>
        <Show when={window.Capacitor.platform === 'android'}>
          <div class={style.mobile}>
            <Alert severity='warning'>
              The app needs to be updated
              <Button
                variant='outlined'
                onclick={() => {
                  Browser.open({
                    url: 'https://dyomedea.app/assets/release/dyomedea.apk',
                  });
                }}
              >
                Update
              </Button>
            </Alert>
          </div>
        </Show>
        <Show when={window.Capacitor.platform === 'web'}>
          <Alert severity='warning' class={style.mobile}>
            Please reload this page to update the application.
          </Alert>
        </Show>
      </Show>
    </>
  );
};

export default Updater;
