import * as Cesium from 'cesium'
import { uid, degToCartesian, degsToCartesians, toCesiumColor, DEFAULT_VECTOR_LAYER_ID } from '@/map/utils/utils'

// deps: { store, layerService }
export function createEntityService(deps) {
  const { store, layerService } = deps

  const svc = {
    _ensureVectorLayer(layerId) {
      const id = layerId || DEFAULT_VECTOR_LAYER_ID
      if (!store.layers[id]) {
        return layerService
          .addLayer({ id, type: 'vector', source: null, options: { visible: true } })
          .then(() => store.layers[id].obj)
      }
      return Promise.resolve(store.layers[id].obj)
    },

    async addPoint(opts) {
      const o = opts || {}
      const ds = await this._ensureVectorLayer(o.layerId)
      const id = o.id || uid('point')
      const ent = new Cesium.Entity({
        id,
        position: degToCartesian(o.position),
        point: {
          pixelSize: o.pixelSize || 8,
          color: toCesiumColor(o.color || '#1E90FF', 1),
          heightReference: o.clampToGround
            ? Cesium.HeightReference.CLAMP_TO_GROUND
            : Cesium.HeightReference.NONE,
        },
        properties: o.properties || {},
      })
      ds.entities.add(ent)
      return id
    },

    async addPolyline(opts) {
      const o = opts || {}
      const ds = await this._ensureVectorLayer(o.layerId)
      const id = o.id || uid('line')
      const ent = new Cesium.Entity({
        id,
        polyline: {
          positions: degsToCartesians(o.positions || []),
          width: o.width || 3,
          material: toCesiumColor(o.color || '#FF4500', 1),
          clampToGround: !!o.clampToGround,
        },
        properties: o.properties || {},
      })
      ds.entities.add(ent)
      return id
    },

    async addPolygon(opts) {
      const o = opts || {}
      const ds = await this._ensureVectorLayer(o.layerId)
      const id = o.id || uid('polygon')
      const ent = new Cesium.Entity({
        id,
        polygon: {
          hierarchy: new Cesium.PolygonHierarchy(degsToCartesians(o.positions || [])),
          material: toCesiumColor(o.fillColor || 'rgba(0,191,255,0.2)'),
          outline: true,
          outlineColor: toCesiumColor(o.outlineColor || '#00BFFF', 1),
          outlineWidth: o.outlineWidth || 1,
          perPositionHeight: !(o.clampToGround === undefined ? true : o.clampToGround),
        },
        properties: o.properties || {},
      })
      ds.entities.add(ent)
      return id
    },

    async addLabel(opts) {
      const o = opts || {}
      const ds = await this._ensureVectorLayer(o.layerId)
      const id = o.id || uid('label')
      const ent = new Cesium.Entity({
        id,
        position: degToCartesian(o.position),
        label: {
          text: o.text || '',
          font: o.font || '14px sans-serif',
          fillColor: toCesiumColor(o.fillColor || '#ffffff', 1),
          outlineColor: toCesiumColor(o.outlineColor || '#000000', 1),
          outlineWidth: o.outlineWidth || 2,
          pixelOffset: o.pixelOffset || new Cesium.Cartesian2(0, -10),
        },
        properties: o.properties || {},
      })
      ds.entities.add(ent)
      return id
    },

    removeEntity(entityId) {
      if (!entityId) return false
      for (const id in store.layers) {
        const rec = store.layers[id]
        if ((rec.type === 'vector' || rec.type === 'datasource') && rec.obj.entities) {
          const e = rec.obj.entities.getById(entityId)
          if (e) {
            rec.obj.entities.remove(e)
            return true
          }
        }
      }
      return false
    },

    getEntity(entityId) {
      if (!entityId) return undefined
      for (const id in store.layers) {
        const rec = store.layers[id]
        if ((rec.type === 'vector' || rec.type === 'datasource') && rec.obj.entities) {
          const e = rec.obj.entities.getById(entityId)
          if (e) return e
        }
      }
      return undefined
    },

    clearLayerEntities(layerId) {
      const id = layerId || DEFAULT_VECTOR_LAYER_ID
      const rec = store.layers[id]
      if (rec && rec.obj && rec.obj.entities) rec.obj.entities.removeAll()
    },
  }

  return svc
}

