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

import RealityKit
import SwiftUI

struct CoordinateConversionVolumeView: View {
    @Environment(AppModel.self) private var appModel

    var body: some View {
        RealityView { content in
            content.add(appModel.volumeRoot)
            appModel.volumeRoot.addChild(appModel.robot)
            appModel.robot.transform = appModel.initialRobotTransform
        } update: { content in
            if appModel.coordianteConverstionState == .fromVolume {
                appModel.immersiveSpaceFromRobot = content.transform(from: appModel.robot, to: .immersiveSpace)
                appModel.robot.setParent(appModel.immersiveRoot)

                appModel.coordianteConverstionState = .toImmersive
            } else if appModel.coordianteConverstionState == .toVolume {
                let immersiveSpaceToRealityKitSpace = content.transform(from: .immersiveSpace, to: .scene)
                appModel.robot.transform = Transform(immersiveSpaceToRealityKitSpace * appModel.immersiveSpaceFromRobot)

                appModel.coordianteConverstionState = .insideVolume

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

                appModel.robot.move(to: targetTransform, relativeTo: nil, duration: 2)
            }
        }
        .toolbar {
            Button {
                appModel.coordianteConverstionState = .fromVolume
            } label: {
                Text("Move to Immersive")
            }
            .disabled(appModel.coordianteConverstionState != .insideVolume)
            Button {
                appModel.coordianteConverstionState = .fromImmersiveSpace
            } label: {
                Text("Move to Volume")
            }
            .disabled(appModel.coordianteConverstionState != .insideImmersiveSpace)
        }
    }
}

#Preview {
    CoordinateConversionVolumeView()
}
