import type { LayerType } from '../../types'
import { DEFAULT_LASSO_TOOLS_LAYER_PROPS } from './const'
import type { LassoToolsLayerProps } from './types'
import deepmerge from 'deepmerge'
import type { FeatureCollection } from 'geojson'
import type { LayerProps } from '@deck.gl/core'
import { CustomEditableGeojsonLayer } from '../custom-editable-geojson-layer'

/**
 * Creates a layer configuration for the lasso tools editable layer.
 *
 * @returns A `LayerType` object with the `CustomEditableGeojsonLayer` type and merged props.
 */
export function getLassoToolsLayer({
  mode,
  ...defaultProps
}: LassoToolsLayerProps & {}): LayerType {
  const props = getLayerProps(defaultProps)

  return {
    type: CustomEditableGeojsonLayer,
    props: {
      ...props,
      mode,
    } as LayerProps,
  }
}

/**
 * Gets the layer props for the MapLassoToolsLayer component.
 * @param layerProps - The layer props.
 * @param onEdit - The onEdit event handler.
 * @param guideColor - The guide color.
 * @returns The layer props for the component.
 */
function getLayerProps({
  layerProps,
  onEdit,
  getLineColor,
  getFillColor,
  pointColor,
}: Omit<LassoToolsLayerProps, 'mode'>) {
  const _layerProps = deepmerge(layerProps, {
    modeConfig: {
      //   // We force distance due to conversion is addressed at feature getText level
      //   formatTooltip: (_distance: number) => {
      //     return _distance
      //   },
      preventOverlappingLines: true,
    },
    onEdit,
  })

  const defaultLayerProps = deepmerge(DEFAULT_LASSO_TOOLS_LAYER_PROPS, {
    getTentativeLineColor: getLineColor,
    getTentativeFillColor: getFillColor,
    getLineColor: getLineColor,
    getFillColor: getFillColor,
    getEditHandlePointColor: pointColor.fill,
    getEditHandlePointOutlineColor: pointColor.outline,
    dataComparator: (data: FeatureCollection, oldData: FeatureCollection) =>
      data.features[0] === oldData.features[0],
  })

  const props = deepmerge(defaultLayerProps, _layerProps)
  return props
}
