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

import RealityKit
import SwiftUI

struct CoordinateConversionImmersiveView: View {
    @Environment(AppModel.self) private var appModel
    @Environment(\.openWindow) private var openWindow
    @Environment(\.dismissWindow) private var dismissWindow

    var body: some View {
        RealityView { content in
            content.add(appModel.immersiveRoot)
        } update: { content in
            if appModel.coordianteConverstionState == .toImmersive {
                let immersiveSpaceToRealityKitSpace = content.transform(from: .immersiveSpace, to: .scene)
                appModel.robot.transform = Transform(immersiveSpaceToRealityKitSpace * appModel.immersiveSpaceFromRobot)

                appModel.coordianteConverstionState = .insideImmersiveSpace

                var targetTransform = appModel.robot.transform
                targetTransform.translation = .init(x: 0, y: 0, z: -1)

                appModel.robot.move(to: targetTransform, relativeTo: nil, duration: 2)
            } else if appModel.coordianteConverstionState == .fromImmersiveSpace {
                appModel.immersiveSpaceFromRobot = content.transform(from: appModel.robot, to: .immersiveSpace)
                appModel.robot.setParent(appModel.volumeRoot)

                appModel.coordianteConverstionState = .toVolume
            }
        }
        .onAppear {
            openWindow(id: AppModel.coordinateConversionWindowId)
        }
        .onDisappear {
            dismissWindow(id: AppModel.coordinateConversionWindowId)
        }
    }
}

#Preview {
    CoordinateConversionImmersiveView()
}
