import { computed } from "vue"

export function useDisplayColor(map) {
  const replaceColorMap = computed(() => {
    return Object.fromEntries(map.value.mapData?.options?.tilecolorReplace?.map(r => [r.sourceColor?.toLocaleLowerCase(), r.targetColor]) ?? [])
  })
  const floor = map.value.getFloorById(getCurrentFloorId())
  const baseAddPolygon = floor.addPolygon.bind(floor)
  const baseAddFaceLine = floor.addFaceLine.bind(floor)
  const baseColorCache = {}

  function overwriteAdd(isChange) {
    function addPolygon(data) {
      if(isChange) {
        return baseAddPolygon(data)
      }

      const replace = {
        ...data,
        color: replaceColorMap.value[data.color?.toLocaleLowerCase()] ?? data.color,
      }
      return baseAddPolygon(replace)
    }

    function addFaceLine() {
      this.data.polygonData.filter(data => data.polygonType === 'faceline' && !data.parentArea)
        .forEach(data => {
          const replaceColor = replaceColorMap.value[data.color?.toLocaleLowerCase()]
          if(replaceColor && !isChange) {
            baseColorCache[data.id] = data.color
            data.color = replaceColor
          } else {
            data.color = baseColorCache?.[data.id] ?? data.color
          }
        })
      baseAddFaceLine()
    }

    return [
      addPolygon,
      addFaceLine,
    ].map(i => i.bind(floor))
  }

  function changeDisplayColor(isChange) {
    ([floor.addPolygon, floor.addFaceLine] = overwriteAdd(isChange))

    floor.rectInstanceMesh?.clearInstances()
    floor.circleInstanceMesh?.clearInstances()
    floor.polygonGroup?.children?.forEach((polygon) =>{
      polygon.dispose()
    })

    floor.initPolgon()
    map.value?.mapTile?.switchBaseColor?.(isChange)
    map.value?.mapTile?.init()
  }

  function getCurrentFloorId() {
    return map.value.status?.floor?.data?.id ?? '1'
  }

  return {
    changeDisplayColor,
  }
}
