import { IonButton, IonIcon, isPlatform } from '@ionic/react';
import { cloudDownload } from 'ionicons/icons';
import React, { Fragment, useRef } from 'react';
import { Filesystem, Directory, Encoding } from '@capacitor/filesystem';
import { useDB } from 'react-pouchdb';
import { getGpxAsXmlString } from '../../db/gpx';

const GpxExport: React.FC<{ gpx: any }> = (props: { gpx: any }) => {
  const db = useDB();

  const isCapacitor = isPlatform('capacitor');
  console.log(`isPlatform('capacitor'): ${isPlatform('capacitor')}`);

  const hiddenLinkElement = useRef<HTMLAnchorElement>(null);

  var downloadName: string;

  if (props.gpx.metadata.name !== undefined) {
    downloadName = props.gpx.metadata.name;
  } else if (props.gpx.gpx.metadata.name !== undefined) {
    downloadName = `${props.gpx.gpx.metadata.name}.gpx`;
  } else {
    downloadName = `track-${props.gpx.metadata.lastModified}.gpx`;
  }

  const download = async (event: any) => {
    event.preventDefault();
    console.log('download()');
    const gpxAsXml = await getGpxAsXmlString(db, props.gpx._id);
    console.log(`gpxAsXml: ${gpxAsXml}`);
    if (isCapacitor) {
      await Filesystem.writeFile({
        path: `Download/${downloadName}`,
        data: gpxAsXml,
        directory: Directory.Documents,
        encoding: Encoding.UTF8,
        recursive: true,
      });
    } else {
      const blob = new Blob([gpxAsXml], {
        type: 'application/gpx+xml',
      });
      const fileDownloadUrl = URL.createObjectURL(blob);
      console.log(`fileDownloadUrl: ${fileDownloadUrl}`);
      console.log(
        `hiddenLinkElement.current, href: ${
          hiddenLinkElement.current!.href
        }, click: ${hiddenLinkElement.current!.click}`
      );
      hiddenLinkElement.current!.href = fileDownloadUrl;
      hiddenLinkElement.current?.click();
      console.log(
        `hiddenLinkElement.current, href: ${
          hiddenLinkElement.current!.href
        }, click: ${hiddenLinkElement.current!.click}`
      );
      URL.revokeObjectURL(fileDownloadUrl);
      hiddenLinkElement.current!.href = '';
    }
  };

  return (
    <Fragment>
      <IonButton id='gpx-export-button' onClick={download}>
        <IonIcon icon={cloudDownload} title='Export' slot='icon-only' />
      </IonButton>
      {isCapacitor && (
        <a className='hidden' download={downloadName} ref={hiddenLinkElement}>
          download
        </a>
      )}
    </Fragment>
  );
};

export default GpxExport;
