//
//  LabelViewController.swift
//  MachineLearningDemo
//
//  Created by Pavel Odstrčilík on 28.04.2021.
//

import Foundation
import UIKit
import Vision
import SnapKit

open class LabelViewController: BaseViewController {

    func showResultsInImage(results: [Any]) {
        imageView.subviews.forEach { $0.removeFromSuperview() }
        for observation in results {
            guard let objectObservation = observation as? VNRecognizedObjectObservation else {
                continue
            }
            let boundingBox = objectObservation.boundingBox
            let size = CGSize(width: boundingBox.width * imageView.bounds.width,
                              height: boundingBox.height * imageView.bounds.height)
            let origin = CGPoint(x: boundingBox.minX * imageView.bounds.width,
                                 y: (1 - objectObservation.boundingBox.minY)
                                    * imageView.bounds.height - size.height)
            let frame = CornerLabelView(frame: CGRect(origin: origin, size: size), text: objectObservation.labels.first?.identifier)
            imageView.addSubview(frame)
        }
    }

    open override func processClassification(request: VNRequest, error: Error?) {
        DispatchQueue.main.async {
            self.activityIndicatorView.stopAnimating()

            guard let results = request.results else {
                return
            }

            if let classifications = results as? [VNRecognizedObjectObservation] {
                self.showResultsInImage(results: classifications)
            }
        }
    }

    open override func prepareResultVisualEffectView() {}
}
