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

import RealityKit
import SwiftUI

struct DirectionalLightView: 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 = .init(x: -0.15, y: -0.2, z: 0)
                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 = "Directional Light"
                lightEntity.components.set(DirectionalLightComponent(color: .yellow, intensity: 3000))
                lightEntity.components.set(DirectionalLightComponent.Shadow())
                lightEntity.transform = Transform(pitch: -.pi / 4, yaw: 0, roll: 0)

                let transform = Transform(pitch: -.pi / 4 + -.pi / 2, yaw: 0, roll: 0)
                let definition = FromToByAnimation(from: transform,
                                                   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 {
    DirectionalLightView()
}
