//
//  VideoPreviewView.swift
//  
//  Copyright © 2016-2019 Apple Inc. All rights reserved.
//

import UIKit
import AVFoundation

extension UIScreen {
    
    var orientation: UIDeviceOrientation {
        let point = coordinateSpace.convert(CGPoint.zero, to: fixedCoordinateSpace)
        if point == CGPoint.zero {
            return .portrait
        } else if point.x != 0 && point.y != 0 {
            return .portraitUpsideDown
        } else if point.x == 0 && point.y != 0 {
            return .landscapeRight //.landscapeLeft
        } else if point.x != 0 && point.y == 0 {
            return .landscapeLeft //.landscapeRight
        } else {
            return .unknown
        }
    }
    
}

class VideoPreviewView: UIView {
    
	var videoPreviewLayer: AVCaptureVideoPreviewLayer {
		return layer as! AVCaptureVideoPreviewLayer
	}
	
	var session: AVCaptureSession? {
		get {
			return videoPreviewLayer.session
		}
		set {
			videoPreviewLayer.session = newValue
		}
	}
    
    var videoOrientation: AVCaptureVideoOrientation? {
        return videoPreviewLayer.connection?.videoOrientation
    }
	
	// MARK: UIView
    override class var layerClass: AnyClass {
		return AVCaptureVideoPreviewLayer.self
	}
    
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        
        videoPreviewLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func updateVideoOrientationFor(deviceOrientation: UIDeviceOrientation) {
        guard let videoPreviewLayerConnection = videoPreviewLayer.connection,
            videoPreviewLayerConnection.isVideoOrientationSupported
            else { return }
        switch (deviceOrientation) {
        case .portrait:
            videoPreviewLayerConnection.videoOrientation = .portrait
        case .landscapeRight:
            videoPreviewLayerConnection.videoOrientation = .landscapeLeft
        case .landscapeLeft:
            videoPreviewLayerConnection.videoOrientation = .landscapeRight
        case .portraitUpsideDown:
            videoPreviewLayerConnection.videoOrientation = .portraitUpsideDown
        default:
            videoPreviewLayerConnection.videoOrientation = .portrait
        }
    }
    
    private func videoOrientationFor(_ deviceOrientation: UIDeviceOrientation) -> AVCaptureVideoOrientation? {
        switch deviceOrientation {
        case .portrait: return AVCaptureVideoOrientation.portrait
        case .portraitUpsideDown: return AVCaptureVideoOrientation.portraitUpsideDown
        case .landscapeLeft: return AVCaptureVideoOrientation.landscapeRight
        case .landscapeRight: return AVCaptureVideoOrientation.landscapeLeft
        default: return nil
        }
    }
}
