//
//  GMCameraFaceView.swift
//  Gengmei
//
//  Created by 刘鹿杰 on 2019/8/17.
//  Copyright © 2019 更美互动信息科技有限公司. All rights reserved.
//

import Foundation

class GMCameraFaceView: GMView {
    //捕获设备，通常是前置摄像头，后置摄像头，麦克风（音频输入）
    var device: AVCaptureDevice!
    //AVCaptureDeviceInput 代表输入设备，他使用AVCaptureDevice 来初始化
    fileprivate var input: AVCaptureDeviceInput!
    //当启动摄像头开始捕获输入
    fileprivate var output: AVCaptureMetadataOutput!
    var ImageOutPut: AVCaptureStillImageOutput!
    //session：由他把输入输出结合在一起，并开始启动捕获设备（摄像头）
    var session: AVCaptureSession!
    //图像预览层，实时显示捕获的图像
    fileprivate var previewLayer: AVCaptureVideoPreviewLayer!
    // 创建中间动画View
    fileprivate var animationView: NewFaceScanAnimationView!
    // 拍照按钮
    fileprivate var shotButton: GMButton!
    // 选择相册按钮
    fileprivate var albumButton: UIButton!
    
    override func setup() {
        customCamera()
        setupSubviews()
    }
    
    func customCamera() {
        if !self.canUseCamera() {
            return
        }
        
        if Platform.isSimulator {
            return
        }
        
        // 使用AVMediaTypeVideo 指明self.device代表视频，默认使用后置摄像头进行初始化
        self.device = AVCaptureDevice.default(for: AVMediaType.video)
        
        // 尝试获取前置摄像头
        for device in AVCaptureDevice.devices(for: AVMediaType.video) where (device as AnyObject).position == .front {
            self.device = device
            break
        }
        
        //使用设备初始化输入
        do {
            self.input = try AVCaptureDeviceInput(device: self.device)
        } catch _ {
        }
        //生成输出对象
        self.output = AVCaptureMetadataOutput()
        self.ImageOutPut = AVCaptureStillImageOutput()
        //生成会话，用来结合输入输出
        self.session = AVCaptureSession()
        if self.session.canSetSessionPreset(AVCaptureSession.Preset.hd1280x720) {
            self.session.sessionPreset = AVCaptureSession.Preset.hd1280x720
        }
        if self.session.canAddInput(self.input) {
            self.session.addInput(self.input)
        }
        if self.session.canAddOutput(self.ImageOutPut) {
            self.session.addOutput(self.ImageOutPut)
        }
        //使用self.session，初始化预览层，self.session负责驱动input进行信息的采集，layer负责把图像渲染显示
        self.previewLayer = AVCaptureVideoPreviewLayer(session: self.session)
        self.previewLayer.frame = CGRect(x: 0, y: 0, width: Constant.screenWidth, height: Constant.screenHeight)
        self.previewLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
        self.layer.insertSublayer(self.previewLayer, at: 0)
        //开始启动
        self.session.startRunning()
        
        do {
            try device.lockForConfiguration()
        } catch _ {
            print("lockForConfiguration failed")
        }
        
        if device.isFlashModeSupported(.off) {
            device.flashMode = .off
        }
        //自动白平衡
        if device.isWhiteBalanceModeSupported(.autoWhiteBalance) {
            device.whiteBalanceMode = .autoWhiteBalance
        }
        device.unlockForConfiguration()
    }
    
    // 改变照相机拍摄方向
    func changeCamera() {
        if !canUseCamera() {
            return
        }
        let cameraCount = AVCaptureDevice.devices(for: AVMediaType.video).count
        if cameraCount <= 1 {
            return
        }
        
        var newCamera: AVCaptureDevice?
        var newInput: AVCaptureDeviceInput?
        if input.device.position == .front {
            newCamera = self.cameraWithPosition(.back)
//            navigationBar.nearRightButton.isHidden = false
        } else {
            newCamera = self.cameraWithPosition(.front)
//            navigationBar.nearRightButton.isHidden = true
        }
        do {
            newInput = try AVCaptureDeviceInput(device: newCamera!)
        } catch let error {
            print("toggle carema failed, error = \(error)")
        }
        
        if newInput != nil {
            session.beginConfiguration()
            session.removeInput(input)
            if session.canAddInput(newInput!) {
                session.addInput(newInput!)
                input = newInput
                device = newCamera
            } else {
                session.addInput(self.input)
            }
            session.commitConfiguration()
        }
    }
    
    
    // 是否可以使用照相机
    func canUseCamera() -> Bool {
        let status = AVCaptureDevice.authorizationStatus(for: AVMediaType.video)
        if status == .denied {
            return false
        } else if status == .notDetermined {
            AVCaptureDevice.requestAccess(for: AVMediaType.video, completionHandler: { (result) in
                if result {
//                    uiThread {
                        self.customCamera()
//                    }
                }
            })
            return false
        } else {
            return true
        }
    }
    
    func cameraWithPosition(_ position: AVCaptureDevice.Position) -> AVCaptureDevice? {
        let devices = AVCaptureDevice.devices(for: AVMediaType.video)
        for device in devices where (device as AnyObject).position == position {
            return device
        }
        return nil
    }
    
    @objc func image(_ image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: UnsafeMutableRawPointer) {
    }
    
    // 设置UI
    func setupSubviews() {
        // 添加动画View
        animationView = NewFaceScanAnimationView(frame: self.bounds)
        self.addSubview(animationView)
        animationView.beginAnimation()
        
        // 拍照按钮
        shotButton = GMButton(type: .custom)
        shotButton.setImage(UIImage(named: "NewFaceShotButton"), for: .normal)
        shotButton.addTarget(self, action: #selector(NewFaceShotController.shotAction), for: .touchUpInside)
        self.addSubview(shotButton)
        
        // 选择照片
        albumButton = UIButton(type: .custom)
        GMNewFaceTool.latestImage { (image) in
            if image == nil {
                DispatchQueue.main.async {
                    self.albumButton.setImage(UIImage(named: "NewFacePhotoNone"), for: .normal)
                    self.albumButton.setImage(UIImage(named: "NewFacePhotoNone"), for: .highlighted)
                }
            } else {
                DispatchQueue.main.async {
                    self.albumButton.setImage(image, for: .normal)
                    self.albumButton.setImage(image, for: .highlighted)
                }
            }
        }
        albumButton.addTarget(self, action: #selector(NewFaceShotController.ablumAction), for: .touchUpInside)
        albumButton.layer.cornerRadius = 4
        albumButton.layer.masksToBounds = true
        albumButton.layer.borderWidth = 1
        albumButton.layer.borderColor = UIColor.white.cgColor
        albumButton.imageView?.contentMode = .scaleAspectFill
        self.addSubview(albumButton)
        
        // 设置拍照按钮动画
        let centerAnimate = CABasicAnimation(keyPath: "transform.rotation.z")
        centerAnimate.toValue = Double.pi * 2.0
        centerAnimate.duration = 2.5
        centerAnimate.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
        centerAnimate.repeatCount = Float(LLONG_MAX)
        shotButton.layer.add(centerAnimate, forKey: "rotation")
        // 更新布局约束
        setupSubviewsConstraints()
    }
    
    func setupSubviewsConstraints() {
        animationView.snp.makeConstraints { (make) in
            make.edges.equalTo(UIEdgeInsets.zero)
        }
        shotButton.snp.makeConstraints { (make) in
            make.bottom.equalTo(-52 - UIView.safeAreaInsetsBottom)
            make.centerX.equalToSuperview()
            make.size.equalTo(CGSize(width: 70, height: 70))
        }
        albumButton.snp.makeConstraints { (make) in
            make.centerY.equalTo(shotButton)
            make.centerX.equalTo(shotButton).offset(-Constant.screenWidth*0.25-12)
            make.size.equalTo(CGSize(width: 46, height: 46))
        }
    }
    
    
    
}
