//
//  PhotoSceneViewController.swift
//  Photolyze
//
//  Created by Mac on 05.09.2019.
//  Copyright (c) 2019 Lammax. All rights reserved.
//
//  This file was generated by the Clean Swift Xcode Templates so
//  you can apply clean architecture to your iOS and Mac projects,
//  see http://clean-swift.com
//

import UIKit
import AVFoundation
//import KPermission
import SPPermissions
import Tweener
import Soundable



class MainSceneViewController: MainExController {
    
    // MARK: VARS
    
    var interactor: PhotoSceneBusinessLogic?
    var router: (NSObjectProtocol & PhotoSceneRoutingLogic & PhotoSceneDataPassing)?
    
    //    var cameraWrap: FilteredCamera!
    var cameraWrap: FilteredCameraBBMetal?
    
    public var cellDelegates: [ImageForFilterDelegate]? = []
    //    private let syncQueue = DispatchQueue(label: "Store Delegate Sync Queue", qos: .userInitiated, attributes: [], autoreleaseFrequency: .workItem)
    public let syncQueue = DispatchQueue(label: "Store Delegate Sync Queue", qos: .userInitiated, attributes: [])
    let semaphore = DispatchSemaphore(value: 1)
    
    //    var YOMOML_dele:CoreForgeDelegate?
    
    
    var photoManagers:PhotoManagersNew!
    
    
    
    // MARK: CONSTANTS
    
    // MARK: OUTLETS
    
    @IBOutlet weak var collectionView: UICollectionView!
    
    @IBOutlet weak var switchCamera: UIImageView!
    @IBOutlet weak var albumBtn: UIImageView!
    
    @IBOutlet weak var shootBtn: CameraButton!
    
    @IBOutlet weak var videoOrphotoSeg: UISegmentedControl!
    var startupGroup = DispatchGroup()
    //屏幕方向
    var deviceMotion:DeviceOrientation!
    
    @IBOutlet weak var videoTimeLabel: UILabel!
    @IBOutlet weak var topContentView: UIView!
    
    @IBOutlet weak var topViewHeight: NSLayoutConstraint!
    @IBOutlet weak var filterHeightCons: NSLayoutConstraint!
    
    
    @IBOutlet weak var bleBtn: UIButton!
    
    @IBOutlet weak var filterBtn: UIButton!
    
    @IBOutlet weak var flashBtn: UIButton!
    
    
    @IBOutlet weak var filterMainStack: UIStackView!
    @IBOutlet weak var filterScrollContainer: UIView!
    @IBOutlet weak var filterNameLabel: UILabel!
    
    @IBOutlet weak var counterLabel: CountdownLabel!
    
    @IBOutlet weak var slideUp: UIView!
    
    @IBOutlet weak var slideDown: UIView!
    
    @IBOutlet weak var slideUpHeight: NSLayoutConstraint!
    private var slideMidY:CGFloat!
    @IBOutlet weak var slideDownHeight: NSLayoutConstraint!
    
    
    @IBAction func toSetting(_ sender: Any) {
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let newVC = storyboard.instantiateViewController(withIdentifier: "Setting")
        AppDelegateMain?.window?.currentViewController()?.navigationController!.pushViewController(newVC, animated: true)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        print("viewWillDisappear")
        if let C = self.cameraWrap{
            C.camera.isPaused = true
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        print("viewWillAppear")
        if let C = self.cameraWrap{
            C.camera.isPaused = false
        }
        
    }
    
    
    @IBAction func photoOrVideoSwitch(_ sender: UISegmentedControl) {
        
        switch sender.selectedSegmentIndex {
        case 0:
            self.shootBtn.btnType = .video
            
        case 1:
            if(!isCameraDenied && self.shootBtn.isSelected){
                self.shootBtn.isSelected = false
                //停止录制
                if let C = self.cameraWrap{
                    C.recordVideo(button: self.shootBtn)
                    self.sendLEDAction(BLE_order.LED.RecordStop)

                }
            }
            isShootSelected = self.shootBtn.isSelected
            self.shootBtn.btnType = .photo
            
        default: break
            
        }
    }
    
    var filterImages = [UIImage]()
    
    func prepareFilterImage(){
        //        let image = UIImage(named: "1")
        
        filterItemsStatic.forEach { (item) in
            if(item != nil){
                let tempImage = item?.filteredImage(with: staticFilterImage!)
                if(!self.filterImages.contains(tempImage!)){
                    self.filterImages.append(tempImage!)
                }
                print("pickerView-filter\(item?.name.lowercased())")
            }else{
                self.filterImages.append(staticFilterImage!)//原图
            }
        }
        if(filterPicker != nil){
            filterPicker.modelImage = self.filterImages
            
            print("setScrollFilter-later\(filterPicker.modelImage)")
        }
        // self.filterPicker.modelImage = self.filterImages
    }
    var filterPicker:CustomUIPickerView!
    func setScrollFilter(){
        
        var temp:[FilterType] = defaultFilters
        if(!temp.contains(FilterType.none)){
            temp.insert(FilterType.none, at: 0)
        }
        
        filterPicker = CustomUIPickerView.init(parentView: self.filterMainStack)
        //        filterPicker.model = defaultFilters
        print("setScrollFilter\(self.filterImages)")
        //        filterPicker.modelImage = self.filterImages
        
        filterPicker.getPickedItem { (index) in
            //隐藏时机？
            self.filterNameLabel.text = temp[index].name_zh()
            if  filterItemsVideo.count > 0{
                //            self.cameraWrap?.addFilter(type: filters[indexPath[1]])
                self.cameraWrap?.addFilter(type: temp[index])
                
            }
            
        }
        //        self.filterMainStack.isHidden = false
        //        self.filterScrollContainer.
        
    }
    
    
    
    // MARK: Object lifecycle
    
    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
        setup()
    }
    var isShootSelected = false
    @IBAction func shootAction(_ sender: Any) {
        takeShoot()
    }
    
    func takeShoot(){
        if(self.shootBtn.btnType == .photo){
            if(isCameraDenied){
                return
            }
            //发起保存图片请求
            //            let request = PhotoScene.StoreCall.Request()
            //            self.interactor?.storeCall(request: request)
            if let C = self.cameraWrap{
                C.takePhoto()
//                self.sendLEDAction(BLE_order.LED.Shoot)//放倒计时那儿

            }
            
        }else{
            if(isCameraDenied){
                return
            }
            if(APP == .Test){
                //                startCountAction()
                
            }
        //开始录制
            //            self.shootBtn.isSelected = !self.shootBtn.isSelected
            if let C = self.cameraWrap{
                C.recordVideo(button: self.shootBtn)
                isShootSelected = self.shootBtn.isSelected
                if(!isShootSelected){
                    self.sendLEDAction(BLE_order.LED.RecordStop)
                }
            }
        }
    }
    
    
    
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setup()
    }
    
    
    
    override func onSound(_ no:Notification){
        let isSound = no.object as! Bool
        print("onSound\(isSound)")
        //        if(isSound){
        //            Soundable.muteAll(for: "dangdang33")
        //        }else{
        //            Soundable.unmuteAll()
        //        }
    }
    
    func startCountAction(){
        
        counterLabel.setCountDownTime(minutes: 3)
        //            counterLabel.defaultFireInterval
        if(self.shootBtn.btnType == .photo){
            self.sendLEDAction(BLE_order.LED.Shoot)

        }else{
            self.sendLEDAction(BLE_order.LED.RecordStart)
        }
        
        counterLabel.animationType = .Scale
        counterLabel.timeFormat = "ss"
        counterLabel.start {
            
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5) {
                
                UIView.animate(withDuration: 0.5) {
                    if(self.hold_task != nil){
                        Soundable.play(fileName: "dangdang33.m4a")
                        
                        if(Global.getLocalData(nameKey: "soundSwitchAction") == "off"){
                            Soundable.muteAll()
                        }else{
                            Soundable.unmuteAll()
                        }
                        //                        soundSwitchAction
                        self.counterLabel.isHidden = false
                    }
                }
                
            }
        }
        counterLabel.completion = {
            DispatchQueue.main.async {
                UIView.animate(withDuration: 0.3) {
                    self.counterLabel.isHidden = true
                    Soundable.stopAll()
                    
                    print("倒计时完成")
                }
                //                self.takeShoot()
                if( self.shootBtn.btnType == .video){
                    self.shootBtn.isSelected = true
                    
                }
                self.shootBtn.sendActions(for: UIControl.Event.touchUpInside)
                
            }
        }
    }
    
    
    override func didEnterBack(noti: Notification) {//完全进入后台
        super.didEnterBack(noti: noti)
        //关闭状态
        //        removeAllTweens()
        //        UIView.animate(withDuration: 1) {
        //            self.slideUp.setY(0)
        //            self.slideDown.setY(self.slideMidY)
        //        }
        
        isInBackGround = true

    }
    override func becomeBack(noti:Notification){
        super.becomeBack(noti: noti)
        //        removeAllTweens()
        isInBackGround = true
        print("becomeBack-override")
        //停止录制
        if(!isCameraDenied && self.shootBtn.isSelected){
            self.shootBtn.isSelected = false
            if let C = self.cameraWrap{
                C.recordVideo(button: self.shootBtn)
                self.sendLEDAction(BLE_order.LED.RecordStop)
            }
        }
        
        self.counterLabel.isHidden = true
        self.counterLabel.cancel()
        
        //        if(!GuideView.needShowGuideView()){
        //            tweenSlide(false)
        //        }
        self.slideDelegate?.showSlide(isOpen: false)
        self.sendMoveHold()//进入后台停止
        Soundable.stopAll()
        self.stopHoldTask()//关闭计时线程
        
        self.isShootSelected = false
    }
    
    override func becomeActive(noti: Notification) {
        super.becomeActive(noti: noti)
        //        removeAllTweens()
        
        isInBackGround = false
        self.slideDelegate?.showSlide(isOpen: true)
        
        //        self.tweenSlide()
        
    }
    
    
    
    // MARK: Setup
    //  UIDevice.orientationDidChangeNotification，手机用户锁定旋转后无效
    private func setup() {
        deviceMotion = DeviceOrientation.init(delegate: self)
        //        PhotoSceneConfigurator.sharedInstance.configure(viewController: self)//放到权限后
        
        //         self.yomolML = CoreMLDelegate.init()
        
    }
    let loadImageOperation = OperationQueue()
    // MARK: View lifecycle
    
    var staticFilterImage:UIImage!
    var closeBtn:UIButton!
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //        checkPermission()
        print("mainview-viewDidLoad")
        slideUpHeight.constant = self.view.frame.height/2 - 50
        slideDownHeight.constant = self.view.frame.height/2 + 50
        
        //        slideMidY = self.slideUp.frame.maxY
        slideMidY = slideUpHeight.constant
        
        
        
        
        // Initialize the cameraWrap.
        //        startupGroup.enter()
        doOnDidLoad()
        self.deviceMotion.startMonitor(OperationQueue.current)
        if(Global.isIphoneX()){
            topViewHeight.constant = 75
            //        filterHeightCons.constant = 70
            filterBtn.transform = filterBtn.transform.translatedBy(x: 0, y: 15)
        }
        
        addCloseBtn()
    }
    
    public func addCloseBtn(){
        closeBtn = UIButton.init(frame: CGRect.init(x: 10, y: self.view.frame.height/8, width: 40, height: 40))
//        closeBtn.backgroundColor = UIColor.red
        closeBtn.setImage(UIImage(named: "close_btn"), for: UIControl.State())
        closeBtn.addTapGestureRecognizer { (tap) in
              AppDelegateMain?.window?.currentViewController()?.navigationController!.popToRootViewController(animated: true)
        }
        self.view.insertSubview(closeBtn, at: 2)
        
    }
    
    
    override func didAllow(permission: SPPermission) {
        super.didAllow(permission: permission)//没有super不会执行父容器里的
        print("didAllow-override\(permission.name)")
        PhotoSceneConfigurator.sharedInstance.configure(viewController: self)
        if(permission.name == "Camera"){
            self.cameraSetup()
            
        }
        if(permission.name == "Photo Library"){
            self.photoManagers = PhotoManagersNew.init(frame: self.albumBtn.frame)
            self.photoManagers.delegate = self
            self.photoManagers.notifyPosterImg()
        }
    }
    override func didDenied(permission: SPPermission) {
        super.didDenied(permission: permission)
        print("didDenied-override")
        
    }
    
    deinit {
        removeAllTweens()
        isCameraSetup = false
        
        if((self.deviceMotion) != nil){
            self.deviceMotion.stop()
            
        }
    }
    
    
    
    // MARK: - UI stuff
    
    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        //        resizePreviewLayer()
    }
    //    override var preferredStatusBarStyle: UIStatusBarStyle {
    //        return .lightContent
    //    }
    func resizePreviewLayer() {
        if(isCameraDenied){
            return
        }
        //        self.cameraWrap.cameraPreviewLayer?.frame = self.view.bounds
    }
    
    
    
    // MARK: UI SETUP
    
    private func gestureSetup() {
        
        //        self.shootBtn.btnType = .video
        self.albumBtn.addTapGestureRecognizer { (tap) in
            print("tapAction-albumBtn\(tap)")
            let picker = DLPhotoPickerViewController.init()
            
            //            picker.delegate = self;
            picker.showsLeftCancelButton = true
            picker.showsNumberOfAssets = true
            //            picker.navigationTitle = NSLocalizedString(@"Albums", nil);
            //            picker.navigationTitle = DLPhotoPickerLocalizedString("Albums", nil)
            picker.pickerType = DLPhotoPickerType.display
            picker.showsEmptyAlbums = false;
            self.present(picker, animated: true) {
                
            }
        }
        
        self.filterBtn.addTapGestureRecognizer { (tap) in
            print("tapAction-filterBtn\(tap)")
            self.filterBtn.isSelected = !self.filterBtn.isSelected
            if let C = self.cameraWrap{
                if(C.currentFilter != nil){
                    self.filterBtn.setImage(UIImage.init(named: "filter_on"), for: UIControl.State.normal)
                }else{
                    self.filterBtn.setImage(UIImage.init(named: "filter_off"), for: UIControl.State.normal)
                    
                }
            }
            if(self.filterBtn.isSelected){
                UIView.animate(withDuration: 1) {
                    self.filterMainStack.isHidden = false
                    
                }
                print("self.filterMainStack-show\(self.filterMainStack.frame)")
                
                
            }else{
                self.filterMainStack.isHidden = true
                
                print("self.filterMainStack\(self.filterMainStack.frame)")
                //                if let C = self.cameraWrap{
                //                    C.addFilter(type:FilterType.none)
                //                    //  selectRow(selectedIndex, inComponent: 0, animated: true)
                //                    self.filterPicker.selectRow(0, inComponent: 0, animated: false)
                //                }
                
            }
            
        }
        self.view.addTapGestureRecognizer { (tap) in
            if(!self.filterMainStack.isHidden){
                self.filterBtn.isSelected = false
                self.filterMainStack.isHidden = true
                if let C = self.cameraWrap{
                    if(C.currentFilter != nil){
                        self.filterBtn.setImage(UIImage.init(named: "filter_on"), for: UIControl.State.normal)
                    }else{
                        self.filterBtn.setImage(UIImage.init(named: "filter_off"), for: UIControl.State.normal)
                        
                    }
                }
            }
        }
        
        self.flashBtn.addTapGestureRecognizer { (tap) in
            print("tapAction-flashBtn\(tap)")
            
            //            self.flashBtn
            
            if let C = self.cameraWrap{
                var flashMode:CameraFlashMode!
                if(self.shootBtn.btnType == .video){
                    flashMode = C.camera.changeFlashMode(cameraOutputMode: CameraOutputMode.video)
                }else{
                    flashMode = C.camera.changeFlashMode(cameraOutputMode: CameraOutputMode.image)
                }
                switch flashMode {
                    
                case .off:
                    self.flashBtn.setImage(UIImage.init(named: "flash_off"), for: UIControl.State.normal)
                case .on:
                    
                    self.flashBtn.setImage(UIImage.init(named: "flash_on"), for: UIControl.State.normal)
                case .auto:
                    
                    self.flashBtn.setImage(UIImage.init(named: "flash_auto"), for: UIControl.State.normal)
                default:
                    self.flashBtn.setImage(UIImage.init(named: "flash_off"), for: UIControl.State.normal)
                }
                
            }
        }
        
        self.switchCamera.addTapGestureRecognizer { (tap) in
            if(self.isCameraDenied){
                return
            }
            print("tapAction-switchCamera\(tap)")
            //            self.cameraWrap.setCameraConfig(isClickSwitch: true)
            if let C = self.cameraWrap{
                C.cameraSwitch()
            }
        }
        
    }
    
    private func collectionSetup() {
        self.collectionView.register(UINib.init(nibName: "FilteredCollectionCell", bundle: nil), forCellWithReuseIdentifier: "filteredCollectionCell")
        self.collectionView.delegate = self
        self.collectionView.dataSource = self
    }
    var isCameraSetup = false
    private func cameraSetup() {
        
        //        self.cameraWrap = FilteredCamera(externalView: self.view){
        //
        //        }
        //        self.cameraWrap?.delegate = self
        //
        if(APP != .Simulator){
            self.cameraWrap = FilteredCameraBBMetal(view: self.view)
            self.cameraWrap?.delegate = self
            print("become-camera")
        }
        isCameraSetup = true
        self.slideDelegate?.showSlide(isOpen: true)
        //        self.slideUp.insertGradientLayer()
        //        tweenSlide()
        
    }
    
    
    override func showSlide(isOpen: Bool) {
        
        if(!GuideView.needShowGuideView() && isCameraSetup){
            DispatchQueue.main.async {
                print("tweenSlide-DispatchQueue--\(self.isInTween)")
                
                self.tweenSlide(isOpen)
            }
            
            
        }
    }
    let semaphoreSlide = DispatchSemaphore(value: 1)
    
    var isInTween = false
    var slide_stateIsOpen = false
    func tweenSlide(_ isOpen:Bool = true){
        if(isInTween || isOpen == slide_stateIsOpen){
            return
        }
        
        //        self.semaphoreSlide.wait()
        isInTween = true
        
        UIView.animate(withDuration: 0.1, animations: {
            print("tweenSlide-before-\(isOpen)\(self.view.frame.height - self.slideMidY)>>\(String(describing: self.slideMidY))>>\(self.slideUp.frame)")
            if(!isOpen){
                //动画开始前确定一下位置
                self.slideUp.setY(-self.slideMidY)
                self.slideDown.setY(self.view.frame.height)
            }else{
                self.slideUp.setY(0)
                self.slideDown.setY(self.slideMidY)
                
            }
        }) { (finish) in
            
            
            
            let downHeight = self.view.frame.height - self.slideMidY
            
            if(!isOpen){
                
                let closeUp = Tween(target:self.slideUp,//Target
                    duration:0.2,//One second
                    ease:Ease.none,
                    to:[.key(\UIView.alpha,1.0),
                          .key(\UIView.transform,self.slideUp.transform.translatedBy(x: 0, y: self.slideMidY)),
                          //This property is an optional.
                        //                            \UIView.backgroundColor!:UIColor.red
                ])
                closeUp.onComplete = {
                    
                }
                closeUp.play()
                
                let closeDown =  Tween(target:self.slideDown,//Target
                    duration:0.2,//One second
                    ease:Ease.none,
                    to:[.key(\UIView.alpha,1.0),
                          .key(\UIView.transform,self.slideDown.transform.translatedBy(x: 0, y:  -downHeight)),
                          //This property is an optional.
                        //                            \UIView.backgroundColor!:UIColor.red
                ])
                closeDown.onComplete = {
                    self.slideUp.setY(0)
                    self.slideDown.setY(self.slideMidY)
                    self.isInTween = false
                    self.slide_stateIsOpen = false//关闭状态
                    print("tweenSlide-close-\(isOpen)\(downHeight)>>\(String(describing: self.slideMidY))>>\(self.slideUp.frame)")
                }
                closeDown.play()
                
                return
            }
            
            
            let openUp =  Tween(target:self.slideUp,//Target
                duration:0.7,//One second
                ease:Ease.none,
                to:[.key(\UIView.alpha,0.8),
                      .key(\UIView.transform,self.slideUp.transform.translatedBy(x: 0, y: -self.slideMidY)),
                      //This property is an optional.
                    //                            \UIView.backgroundColor!:UIColor.red
            ])
            openUp.onComplete = {
                
            }
            openUp.play()
            let openDown =  Tween(target:self.slideDown,//Target
                duration:0.7,//One second
                ease:Ease.none,
                to:[.key(\UIView.alpha,0.8),
                      .key(\UIView.transform,self.slideDown.transform.translatedBy(x: 0, y: downHeight)),
                      //This property is an optional.
                    //                            \UIView.backgroundColor!:UIColor.red
            ])
            openDown.onComplete = {
                self.slideUp.setY(-self.slideMidY)
                self.slideDown.setY(self.view.frame.height)
                self.isInTween = false
                self.slide_stateIsOpen = true//打开状态
                
                print("tweenSlide-open\(isOpen)\(downHeight)>>\(String(describing: self.slideMidY))>>\(self.slideUp.frame)")
                
            }
            openDown.play()
        }
        self.isArcActive()
        if(Global.getLocalData(nameKey: "privacy") == EMPTYVARCHAR){//第一次
            self.view.privacyDialog(isFirst: true)
        }
        
    }
    
    
    
    
    override func awakeFromNib() {
        print("mainview-awakeFromNib")
    }
    
    // MARK: Do some local logic
    
    private func doOnDidLoad() {
        //  self.cameraSetup()
        bleBtn.isSelected = false
        self.gestureSetup()
        //        self.collectionSetup()//滑动切换滤镜
        self.setScrollFilter()
        
        //加载耗时-background:6s\userInteractive:2.7s\userInitiated:2.8s\utility:3.0s
        //        loadImageOperation.qualityOfService = .background
        loadImageOperation.qualityOfService = .userInitiated
        loadImageOperation.maxConcurrentOperationCount = 8
        let addVideoFilter = BlockOperation()
        let addPhotoFilter = BlockOperation()
        let addStatic = BlockOperation()
        addVideoFilter.addExecutionBlock {
            filterItemsVideo = FilterManager.sharedInstance.getFilterList()
        }
//        addPhotoFilter.addExecutionBlock {
//            filterItemsPhoto = FilterManager.sharedInstance.getFilterList()
//        }
        addStatic.addExecutionBlock {
            self.staticFilterImage = UIImage.init(named: "sunflower")

            filterItemsStatic = FilterManager.sharedInstance.getFilterList()
            if(APP != .Simulator){
                self.prepareFilterImage()
            }
            
        }
        loadImageOperation.addOperation(addVideoFilter)
        loadImageOperation.addOperation(addStatic)
        loadImageOperation.addOperation(addPhotoFilter)
        
        
        
        // Initialize the neural network.
        
        //Forge##
        //        startupGroup.enter()
        //        YOMOML_dele = CoreForgeDelegate.init()
        //        YOMOML_dele!.preview = self.view
        //        YOMOML_dele!.createNeuralNetwork {
        //            self.startupGroup.leave()
        //        }
        
        //        CoreML
        
        
        //        yomolML?.addBoxToView()
        
        // Once the NN is set up, we can start capturing live video.
        //        startupGroup.notify(queue: .main) {
        //            // NOTE: At this point you'd remove the spinner and enable the UI.
        ////            fpsCounter.start()
        //            //            self.videoCapture.start()
        ////            self.cameraWrap?.startRunningCaptureSession()
        ////            self.cameraWrap?.start()
        //
        //        }
        
        
        //Forge##
        //        startupGroup.notify(queue: .main) {
        //            self.YOMOML_dele?.addBoxToView()
        //        }
        
    }
    
    override func onWifi(_ no: Notification) {
        if let bleState = no.object as? Bool{
            bleBtn.isSelected = bleState
        }
    }
    
    
    //VIPER stuff
    private func storePhoto(image: CIImage?) {
        let request = PhotoScene.StorePhoto.Request(image: image)
        self.interactor?.storePhoto(request: request)
    }
    
    private var hold_task:Task?
    
    /**
     开始计时线程
     */
    func startHoldTask(_ distance:CGFloat){
        if(hold_task == nil && !isShootSelected && slide_stateIsOpen){
            print("startHoldTask")
            hold_task = delayDemo().delay(1.5) {
                print("延迟两/一秒")
                if(distance >= 0){//两秒后再判断一下？
                    self.startCountAction()
                }
            }
        }
    }
    
    /**
     关闭计时线程
     */
    func stopHoldTask(){
        if(hold_task != nil){
            print("stopHoldTask")
            delayDemo().cancel(hold_task)
            Soundable.stopAll()
            
            DispatchQueue.main.async {
                self.counterLabel.cancel {
                    UIView.animate(withDuration: 0.1) {
                        self.counterLabel.isHidden = true
                        self.hold_task = nil
                    }
                }
                
            }
            
        }
    }
    
    
}

extension MainSceneViewController: PhotoSceneDisplayLogic {
    func displaySavePhoto(viewModel: PhotoScene.StoreCall.ViewModel) {//图片保存相册成功反馈
        self.present(viewModel.alertController, animated: true, completion: nil)
    }
    
    func displayStorePhoto(viewModel: PhotoScene.StorePhoto.ViewModel) {
        //smth for display for photo store case
    }
}


//extension PhotoSceneViewController: FilteredCameraDelegate {
extension MainSceneViewController: FilteredCameraBBMetalDelegate {
    func metaCapture(_ capture: FilteredCameraBBMetal, faceBoxes: NSMutableArray, didOutputMetadataObjects: [AVMetadataObject]) {
        
        
    }
    //coreML
    func videoCapture(_ capture: FilteredCameraBBMetal, didCaptureVideoFrame: CVPixelBuffer?, timestamp: CMTime) {
    }
    //    Forge##
    func videoCapture(_ capture: FilteredCameraBBMetal, didCaptureVideoTexture texture: MTLTexture?, timestamp: CMTime) {
    }
    
    func filteredCamera(didUpdate image: CIImage) {
        var tempDelegates: [ImageForFilterDelegate]? = []
        syncQueue.sync {
            self.semaphore.wait()
            tempDelegates = self.cellDelegates
            //放进同步里
            if let delegates = tempDelegates {
                for delegate in delegates {
                    delegate.update(with: image)
                    //bug->>>感觉在时刻盼望，等待被点击事件保存。。。耗内存
                    //                          self.storePhoto(image: delegate.currentFilteredImage)//处理照相请求
                }
            }
            self.semaphore.signal()
        }
        
    }
    
    
    func faceMove(_ direction: BLE_order.Direction, distance: CGFloat) {
        if(isDeviceCorrect != true){
            return
        }
        print("faceMove-dele\(direction == .Hold_Left ? "左" : "右")>>\(distance)")
        if(distance < 0){//超界无指令自动停
            self.stopHoldTask()
            return
        }
        if(distance == 0){
            self.sendMoveHold()
            self.startHoldTask(distance)
            
        }else{
            self.sendMoveFast(direction)
            self.stopHoldTask()
            
            //            self.sendMoveSlow(direction)
            
        }
    }
    
    
}

extension MainSceneViewController: DeviceOrientationDelegate {
    
    func directionChange(_ direction: TgDirection) {
        deviceOrientation = direction
        
        print("PhotoSceneViewController-directionChange\(deviceOrientation.rawValue)")
        switch direction {
        case .directionPortrait:
            DispatchQueue.main.async {
                //                self.counterLabel.transform =  .identity
                UIView.animate(withDuration: 0.7) {
                    self.counterLabel.transform = .identity
                    self.bleBtn.transform =  .identity
                    
                    self.filterBtn.transform =  .identity
                    
                    self.flashBtn.transform =  .identity
                    self.albumBtn.transform =  .identity
                    self.switchCamera.transform =  .identity
                }
            }
        case .directionleft:
            
            DispatchQueue.main.async {
                
                //                self.counterLabel.transform =  self.counterLabel.transform.rotated(by:CGFloat(Float.pi/2))
                UIView.animate(withDuration: 0.7) {
                    self.counterLabel.transform =  self.counterLabel.transform.rotated(by: CGFloat(Float.pi/2))
                    //                     self.counterLabel.transform =  self.counterLabel.transform.translatedBy(x: 0, y: self.view.center.x - self.counterLabel.center.x)
                    //
                    self.bleBtn.transform =  self.bleBtn.transform.rotated(by: CGFloat(Float.pi / 2))
                    
                    self.filterBtn.transform =  self.filterBtn.transform.rotated(by: CGFloat(Float.pi / 2))
                    
                    self.flashBtn.transform =  self.flashBtn.transform.rotated(by: CGFloat(Float.pi / 2))
                    /**
                     跟着转？？？
                     */
                    //                    self.albumBtn.transform =  self.counterLabel.transform.rotated(by: CGFloat(Float.pi * 2))
                    //                    self.switchCamera.transform =  self.counterLabel.transform.rotated(by: CGFloat(Float.pi * 2))
                    
                    self.albumBtn.transform =  self.albumBtn.transform.rotated(by: CGFloat(Float.pi / 2))
                    self.switchCamera.transform =  self.switchCamera.transform.rotated(by: CGFloat(Float.pi / 2))
                }
            }
        case .directionRight:
            
            DispatchQueue.main.async {
                //                self.counterLabel.center = self.view.center
                
                UIView.animate(withDuration: 0.7) {
                    self.counterLabel.transform =  self.counterLabel.transform.rotated(by: CGFloat(-Float.pi/2))
                    
                    //                    self.counterLabel.transform =  self.counterLabel.transform.translatedBy(x: 0, y: self.view.center.x - self.counterLabel.center.x)
                    //
                    self.bleBtn.transform =  self.bleBtn.transform.rotated(by: CGFloat(-Float.pi / 2))
                    
                    self.filterBtn.transform =  self.filterBtn.transform.rotated(by: CGFloat(-Float.pi / 2))
                    
                    self.flashBtn.transform =  self.flashBtn.transform.rotated(by: CGFloat(-Float.pi / 2))
                    self.albumBtn.transform =  self.albumBtn.transform.rotated(by: CGFloat(-Float.pi / 2))
                    self.switchCamera.transform =  self.switchCamera.transform.rotated(by: CGFloat(-Float.pi / 2))
                }
                
            }
            
        case .directionDown: break
            
        default:
            break
        }
        
        
    }
    
    
    
}


// MARK: SPPermissions Data Source & Delegate

extension MainSceneViewController: PhotoManagersDelegateNew {
    //相册最新图片
    func getLatestImg(image: UIImage?) {//变化监听
        DispatchQueue.main.async {
            self.albumBtn.image = image
        }
    }
    
}



