import { useI18n } from '@solid-primitives/i18n';
import { Grid, Typography } from '@suid/material';
import { Component, createSignal, Show } from 'solid-js';
import { findStartTime } from '../../lib/gpx';
import GPX from '../../lib/gpx-parser-builder/src/gpx';

interface Props {
  gpxFile: File;
}

const analyzeGpx = (gpx: Gpx | undefined) => {
  if (gpx === undefined) {
    return {};
  }
  const stats = {
    creator: gpx.$.creator,
    nbWpts: gpx.wpt ? gpx.wpt?.length : 0,
    nbRtes: gpx.rte ? gpx.rte?.length : 0,
    nbTrks: gpx.trk ? gpx.trk?.length : 0,
  };
  return stats;
};

const GpxImportSingleFile: Component<Props> = ({ gpxFile }) => {
  const [t] = useI18n();
  const [gpx, setGpx] = createSignal<Gpx>();

  const gpxReader = new FileReader();
  gpxReader.readAsText(gpxFile);

  gpxReader.addEventListener(
    'load',
    async () => {
      // this will then display a text gpxfile
      console.log({
        caller: 'GpxImportSingleFile / XML',
        gpxFile,
        result: gpxReader.result,
      });
      const gpx = GPX.parse(gpxReader.result);
      console.log({ caller: 'GpxImportSingleFile / JSON', gpxFile, gpx });
      setGpx(gpx);
      //   if (gpx) {
      //     const startTime = new Date(findStartTime(gpx)!);
      //   }
    },
    false
  );

  const stats = analyzeGpx(gpx());

  return (
    <Grid container spacing={2}>
      <Grid item xs={12}>
        <Typography variant='subtitle1'>
          {t('file')}
          {gpxFile.name}
        </Typography>
      </Grid>
      <Show when={gpx() !== undefined}>
        <Grid item xs={12}>
          <Typography variant='body1'>
            {t('gpxStats', analyzeGpx(gpx()))}
          </Typography>
        </Grid>
      </Show>
    </Grid>
  );
};

export default GpxImportSingleFile;
