import SwiftUI
import Vision

struct ContentView: View {
   @State private var bodyPose: String = "Detecting..."

   var body: some View {
      VStack {
         VStack {
            Image(uiImage: UIImage(named: "twohands")!)
               .resizable()
               .scaledToFit()
            Text(bodyPose)
               .padding()
            Spacer()
         }
         .padding()
         .task {
            let imageURL = Bundle.main.url(forResource: "twohands", withExtension: "png")
            if let imageURL = imageURL {
               do {
                  let request = DetectHumanBodyPoseRequest()
                  let observations = try await request.perform(on: imageURL)
                  
                  var text = ""
                  for (index, observation) in observations.enumerated() {
                     text += "Person \(index + 1)\n"
                     
                     if let leftHand = observation.joint(for: .leftWrist), let leftElbow = observation.joint(for: .leftElbow) {
                        if leftHand.location.y > leftElbow.location.y {
                           text += "Left hand raised\n"
                        }
                     }
                     if let rightHand = observation.joint(for: .rightWrist), let rightElbow = observation.joint(for: .rightElbow) {
                        if rightHand.location.y > rightElbow.location.y {
                           text += "Right hand raised\n"
                        }
                     }
                  }
                  bodyPose = text
               } catch {
                  print("Error performing the request: \(error)")
               }
            }
         }
      }
      .padding()
   }
}