import "pannellum"

import { Feature, Geometry, Point } from "geojson"
import { GeoOperations } from "../../Logic/GeoOperations"
import { HotspotProperties, PanoramaView } from "../../Logic/ImageProviders/ImageProvider"
import { Store, UIEventSource } from "../../Logic/UIEventSource"

export class PhotoSphereViewerWrapper {
    private _imageInfo: UIEventSource<NonNullable<Feature<Point, PanoramaView>>> = new UIEventSource(undefined)
    public imageInfo: Store<NonNullable<Feature<Point, PanoramaView>>> = this._imageInfo
    private readonly viewer: Pannellum.Viewer
    private nearbyFeatures: Feature<Geometry, HotspotProperties>[] = []

    /**
     *
     * @param container The HTML-element to bind to
     * @param imageInfo An eventSource containing the panorama-info. Might be changed by this component if walking around;
     * @param nearbyFeatures Nearby features to show a point about, e.g. to walk around
     */
    constructor(
        container: HTMLElement,
        imageInfo: Feature<Point, PanoramaView>,
        nearbyFeatures?: Feature<Geometry, HotspotProperties>[]
    ) {
        this._imageInfo.set(imageInfo)
        this.viewer = pannellum.viewer(container, <any>{
            default: {
                firstScene: imageInfo.properties.url,
                sceneFadeDuration: 250,
            },
            scenes: {
                [imageInfo.properties.url]: {
                    type: "equirectangular",
                    hfov: 110,
                    panorama: imageInfo.properties.url,
                    autoLoad: true,
                    hotSpots: [],
                    sceneFadeDuration: 250,
                    compass: true,
                    showControls: false,
                    northOffset: imageInfo.properties.northOffset,
                    horizonPitch: imageInfo.properties.pitchOffset
                },
            },
        })

        this.setNearbyFeatures(nearbyFeatures)

    }

    public calculatePitch(feature: Feature): number {
        const coors = this.imageInfo.data.geometry.coordinates
        const distance = GeoOperations.distanceBetween(
            coors,
            GeoOperations.centerpointCoordinates(feature)
        )

        // In: -pi/2 up to pi/2
        /*
          .                           + Eye
          .                       /   |
          .                  /  PITCH |
          .           /               | (Height = y = ~2m)
          .      /                    |
          ./ ALPHA                    |
          +..... (x = distance) .... +
         */
        const height = 3
        // We want to know PITCH = 90 - alpha.
        //
        // tan(alpha) = height / distance (we rescale so that distance -> 1)
        // alpha = atan(height / distance)
        const alpha = Math.atan(height / distance) // in radians
        const degrees = (alpha * 360) / (2 * Math.PI)
        return -degrees
    }

    private setPanorama(imageInfo: Feature<Point, PanoramaView>) {
        if (this.viewer?.getScene() === imageInfo?.properties?.url) {
            // Already the current scene
            return
        }
        this.clearHotspots()
        this.viewer.addScene(imageInfo.properties.url, <any>{
            panorama: imageInfo.properties.url,
            northOffset: imageInfo.properties.northOffset,
            type: "equirectangular",
            showControls: false,
        })

        this.viewer.loadScene(imageInfo.properties.url, 0, imageInfo.properties.northOffset)
        this.setNearbyFeatures(this.nearbyFeatures)
        this._imageInfo.set(imageInfo)

    }

    private clearHotspots() {
        const currentUrl = this.imageInfo.data.properties.url
        const hotspots = this.viewer.getConfig()["scenes"][currentUrl].hotSpots ?? []
        for (const hotspot of hotspots) {
            this.viewer.removeHotSpot(hotspot?.id, currentUrl)
        }
    }

    public setNearbyFeatures(nearbyFeatures: Feature<Geometry, HotspotProperties>[]) {
        const imageInfo = this.imageInfo.data
        if (!this.imageInfo) {
            return
        }
        const northOffs = imageInfo.properties.northOffset
        this.nearbyFeatures = nearbyFeatures
        this.clearHotspots()
        const centralImageLocation = imageInfo.geometry.coordinates
        for (const f of nearbyFeatures ?? []) {
            if (f.properties.gotoPanorama?.properties?.url === imageInfo.properties.url) {
                continue // This is the current panorama, no need to show it
            }
            const yaw = GeoOperations.bearing(imageInfo, GeoOperations.centerpoint(f))
            let pitch = 0
            if (f.properties.pitch === "auto") {
                pitch = this.calculatePitch(f)
            } else if (!isNaN(f.properties.pitch)) {
                pitch = f.properties.pitch
            }
            const distance = Math.round(
                GeoOperations.distanceBetween(
                    centralImageLocation,
                    GeoOperations.centerpointCoordinates(f)
                )
            )
            this.viewer.addHotSpot(
                {
                    type: f.properties.gotoPanorama !== undefined ? "scene" : "info",
                    yaw: (yaw - northOffs) % 360,
                    pitch,
                    text: f.properties.name + " (" + distance + "m)",
                    clickHandlerFunc: () => {
                        this.setPanorama(f.properties.gotoPanorama)
                    },
                },
                imageInfo.properties.url
            )
            if (f.properties.focus) {
                this.viewer.setYaw(yaw - northOffs)
            }
        }
    }
}
