import { Component, createEffect } from 'solid-js';

import style from './index.module.css';
import Tree from '../tree/Tree';
import getUri from '../../lib/ids';
import { createCachedSignal } from '../../workers/cached-signals';
import { FormControlLabel, Radio, RadioGroup } from '@suid/material';
import { getDrawingSelections } from '../../db/drawing-selections';
import dispatch from '../../workers/dispatcher-main';
import { Feature } from 'ol';
import uri from '../../lib/ids';

const id = getUri('drawingSelections', undefined);

type SelectionType = 'ALL' | 'NONE' | 'CURRENT';

type DrawingSelections = {
  gpxSelection: SelectionType;
  trkSelection: SelectionType;
  wptSelection: SelectionType;
};

const defaultDrawingSelections: DrawingSelections = {
  gpxSelection: 'ALL',
  trkSelection: 'ALL',
  wptSelection: 'ALL',
};

const drawingSelections = createCachedSignal({
  id,
  method: 'getDrawingSelections',
  defaultDrawingSelections,
}) as () => DrawingSelections;

createEffect(() => {
  console.log({
    caller: 'DrawingSelections',
    drawingSelections: drawingSelections(),
  });
});

const AllNoneCurrent: Component<{}> = (props) => {
  return (
    <>
      <FormControlLabel
        value='ALL'
        control={<Radio />}
        label='All'
      ></FormControlLabel>
      <FormControlLabel
        value='NONE'
        control={<Radio />}
        label='None'
      ></FormControlLabel>
      <FormControlLabel
        value='CURRENT'
        control={<Radio />}
        label='Current'
      ></FormControlLabel>
    </>
  );
};

export const mustBeDrawn = (feature: Feature) => {
  const id = feature.getId();
  const type = feature.get('type');
  const idObj = uri(type, id);
  const gpxId = idObj.gpx;
  console.log({
    caller: 'DrawingSelector / mustBeDrawn',
    feature,
    type,
    id,
    idObj,
    gpxId,
  });
  if (drawingSelections().gpxSelection === 'ALL') return true;
  return false;
};

const handleGpxSelectionChange = (ev: any) => {
  const value = ev.target.value;
  console.log({
    caller: 'DrawingSelector / handleGpxSelectionChange',
    ev,
    value,
  });
  const newDrawingSelections = drawingSelections();
  newDrawingSelections.gpxSelection = value;
  dispatch({
    action: 'putDrawingSelections',
    params: { id, drawingSelections: newDrawingSelections },
  });
};

const DrawingSelector: Component<{}> = (props) => {
  return (
    <Tree
      title='Show'
      content={
        <>
          <div>Trips</div>
          <RadioGroup
            defaultValue={drawingSelections()?.gpxSelection}
            onChange={handleGpxSelectionChange}
          >
            <AllNoneCurrent />
          </RadioGroup>
        </>
      }
      subTree={undefined}
    />
  );
};

export default DrawingSelector;
