import React from 'react';

import { useDispatch } from 'react-redux';

import GPX from '../../lib/gpx-parser-builder';

import '../../theme/get-location.css';
import { IonIcon, IonItem } from '@ionic/react';
import { downloadSharp } from 'ionicons/icons';
import { tracksActions } from '../../store/tracks';

const GpxImport: React.FC<{}> = () => {
  const dispatch = useDispatch();

  const onChangeHandler = (event: any) => {
    console.log('On change handler');
    const file: File = event.target.files[0];
    const fileReader = new FileReader();
    fileReader.readAsText(file);

    fileReader.addEventListener(
      'load',
      () => {
        // this will then display a text file
        console.log(fileReader.result);
        const track = GPX.parse(fileReader.result);
        dispatch(
          tracksActions.push({
            track: JSON.parse(JSON.stringify(track)),
            metadata: {
              lastModified: new Date(file.lastModified).toISOString(),
              importDate: new Date().toISOString(),
              name: file.name,
              size: file.size,
              type: file.type,
            },
          })
        );
      },
      false
    );
  };

  return (
    <IonItem>
      <input
        type='file'
        id='gpx-import'
        className='input-file'
        accept='.gpx'
        onChange={onChangeHandler}
      />
      <label htmlFor='gpx-import'>
        <IonIcon slot='icon-only' icon={downloadSharp} />
      </label>
    </IonItem>
  );
};

export default GpxImport;
