import react, { useMemo, useEffect, useState } from 'react';
import { useDispatch } from 'react-redux';
import { mapActions } from '../../store/map';
import _ from 'lodash';
import { useDB } from 'react-pouchdb';

import Layer from '../slippy/layer';
import Slippy from '../slippy/slippy';
import TiledMap from './tiled-map';
import GetLocation from './get-location';
import Whiteboard from './whiteboard';
import CurrentLocation from './current-location';
import {
  IonApp,
  IonButtons,
  IonContent,
  IonFooter,
  IonHeader,
  IonToolbar,
} from '@ionic/react';

import Gpxes from './gpxes';
import GpxRecord from './gpx-record';
import { initDb } from '../../db';
import TileServerChooserButton from './TileServerChooserButton';
import TileServerChooserDialog from './TileServerChooserDialog';
import TrackBrowser from './TracksBrowser';

const Map: react.FC<{}> = (props: {}) => {
  const dispatch = useDispatch();

  const resizeHandler = () => {
    dispatch(mapActions.resize());
  };
  const debouncedResizeHandler = useMemo(
    () => _.debounce(resizeHandler, 500),
    []
  );

  const db = useDB();

  const [dbReady, setDbReady] = useState(false);

  useEffect(() => {
    window.addEventListener('resize', debouncedResizeHandler);
    initDb(db, setDbReady);
  }, []);

  return (
    <>
      <IonContent fullscreen={true}>
        <IonApp>
          <TileServerChooserDialog />
          <Slippy>
            <Whiteboard>
              <CurrentLocation />
              dbReady && <Gpxes />
            </Whiteboard>
            <Layer>
              <TiledMap />
            </Layer>
          </Slippy>
        </IonApp>
      </IonContent>
      <IonHeader className='ion-no-border' translucent={true}>
        <IonToolbar>
          <IonButtons slot='end'>
            <TrackBrowser/>
            <GpxRecord />
            <TileServerChooserButton />
          </IonButtons>
        </IonToolbar>
      </IonHeader>
      <IonFooter className='ion-no-border'>
        <IonToolbar>
          <IonButtons>
            <GetLocation />
          </IonButtons>
        </IonToolbar>
      </IonFooter>
    </>
  );
};

export default Map;
