//
//  Heise Vision Pro
//  Copyright © 2024 Gero Gerber. All rights reserved.
//

import RealityKit
import SwiftUI

struct SpotLightView: View {
    var body: some View {
        RealityView { content in
            do {
                let robot = try await Entity(named: "drummer")
                robot.name = "Robot"
                robot.position.x = 0.15
                robot.position.y = -0.2
                robot.playAnimation(robot.availableAnimations[0].repeat(),
                                    transitionDuration: 0.5,
                                    startsPaused: false)
                content.add(robot)

                let plane = try await Entity(named: "plane")
                plane.name = "Plane"
                plane.position.x = -0.15
                plane.position.y = -0.2
                plane.components.set(DynamicLightShadowComponent(castsShadow: true))
                plane.playAnimation(plane.availableAnimations[0].repeat(),
                                    transitionDuration: 0.5,
                                    startsPaused: false)
                content.add(plane)

                let groundPlane = ModelEntity(mesh: MeshResource.generatePlane(width: 1, depth: 1), materials: [SimpleMaterial(color: .gray, isMetallic: false)])
                groundPlane.name = "Ground Plane"
                groundPlane.position.y = -0.25
                groundPlane.components.set(DynamicLightShadowComponent(castsShadow: false))
                content.add(groundPlane)

                let lightEntity = Entity()
                lightEntity.name = "Spotlight"
                lightEntity.components.set(SpotLightComponent(color: .white, intensity: 1000, outerAngleInDegrees: 70))
                lightEntity.components.set(SpotLightComponent.Shadow())

                var initialTransform = Transform(pitch: -.pi / 4, yaw: 0, roll: 0)
                initialTransform.translation.y = 0.5

                lightEntity.transform = initialTransform

                var targetTransform = Transform(pitch: -.pi / 4 + -.pi / 2, yaw: 0, roll: 0)
                targetTransform.translation.y = 0.5

                let definition = FromToByAnimation(from: targetTransform,
                                                   duration: 2,
                                                   timing: .easeInOut,
                                                   bindTarget: .transform,
                                                   repeatMode: .autoReverse)

                if let animate = try? AnimationResource.generate(with: definition) {
                    lightEntity.playAnimation(animate)
                }

                content.add(lightEntity)
            } catch {
                print(error)
            }
        }
    }
}

#Preview {
    SpotLightView()
}
