import SwiftUI
import Vision

struct ContentView: View {
   @State private var observations: [HumanBodyPoseObservation] = []

   var body: some View {
      VStack {
         Button("Detect") {
            Task {
               await detectBodies()
            }
         }.buttonStyle(.borderedProminent)

         Canvas { context, size in
            // Calculate size and draw image
            let image = UIImage(named: "twopeople")!
            let width = size.width
            let height = image.size.height * width / image.size.width
            let imageFrame = CGRect(origin: .zero, size: CGSize(width: width, height: height))
            context.draw(Image(uiImage: image), in: imageFrame)

            // Show points
            for observation in observations {
               let points = observation.allJoints()
               for (_, value) in points {
                  let location = value.location
                  let point = location.toImageCoordinates(imageFrame.size, origin: .upperLeft)
                  let circleFrame = CGRect(x: point.x - 3, y: point.y - 3, width: 6, height: 6)
                  context.fill(Circle().path(in: circleFrame), with: .color(.green))
               }
            }
         }
         Spacer()
      }
      .padding()
   }
   func detectBodies() async {
      let imageURL = Bundle.main.url(forResource: "twopeople", withExtension: "png")
      if let imageURL = imageURL {
         do {
            let request = DetectHumanBodyPoseRequest()
            observations = try await request.perform(on: imageURL)
         } catch {
            print("Error performing the request: \(error)")
         }
      }
   }
}