//
//  ViewController.swift
//  HeadNavigationClient
//
//  Created by Sergii Kryvoblotskyi on 5/20/21.
//

import Cocoa
import AVFoundation
import CoreMotion

final class ViewController: NSViewController {
    
    var timer: Timer?
    var headThreshold: Double = 0.4
    var headThresholdCorrection: Double = 0.5
    var isHandlingGesture: Bool = true
//    let manager = CMHeadphoneMotionManager()

    private let browser = ServersBrowser()
    private var connection: BonjourConnection?
    private let keyboard = Keyboard()
    
    private var player: AVPlayer?
    
    @IBOutlet weak var videoView: NSView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupView()
        browser.onServersChanged = { [weak self] servers in
            self?.stopConnection()
            if let server = servers.first {
                self?.startConnection(service: server)
            }
        }
        browser.start()
//
    }

    @IBAction func upButtonClicked(_ sender: Any) {
        playVideo(from: 0, to: 2)
    }
    
    @IBAction func rightButtonClicked(_ sender: Any) {
        playVideo(from: 2, to: 4)
    }
    
    @IBAction func leftButtonClicked(_ sender: Any) {
        playVideo(from: 4, to: 6)
    }
    
    @IBAction func downButtonClicked(_ sender: Any) {
        playVideo(from: 6, to: 8)
    }
    
    @IBAction func enterButtonClicked(_ sender: Any) {
        playVideo(from: 12.8, to: 16)
    }
    
    @IBAction func escapeButtonClicked(_ sender: Any) {
        playVideo(from: 9, to: 12)
    }
}

extension ViewController {
    
    func setupView() {
        videoView.wantsLayer = true
        
        let path = Bundle.main.url(forResource: fileName, withExtension: "mp4")!
        let player = AVPlayer(url: path)
        self.player = player
        let playerLayer = AVPlayerLayer(player: player)
        
        playerLayer.frame = videoView.bounds.insetBy(dx: 40, dy: 40)
        videoView.layer!.addSublayer(playerLayer)
    }
    
    func playVideo(from time: TimeInterval, to endTime: TimeInterval) {
        
        let path = Bundle.main.url(forResource: fileName, withExtension: "mp4")!
        let item = AVPlayerItem(url: path)
        let player = AVPlayer(playerItem: item)
        self.player = player
        
        let playerLayer = AVPlayerLayer(player: player)
        playerLayer.frame = videoView.bounds.insetBy(dx: 40, dy: 40)
        videoView.layer!.addSublayer(playerLayer)
        
        player.seek(to: CMTimeMakeWithSeconds(time, preferredTimescale: 1), toleranceBefore: CMTime.zero, toleranceAfter: CMTime.zero)
        item.forwardPlaybackEndTime = CMTimeMakeWithSeconds(endTime, preferredTimescale: 1)
        player.play()
        
        DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
            self.videoView.layer?.sublayers?.first?.removeFromSuperlayer()
        }
    }
}

extension ViewController {
    
    var isDarkMode: Bool {
        return self.view.isDarkMode
    }
    
    var fileName: String {
        return isDarkMode ? "HeadWithAirPodsOnBlack" : "HeadWithAirPodsOnWhite"
    }
}

extension NSView {
    
    var isDarkMode: Bool {
        if #available(OSX 10.14, *) {
            if effectiveAppearance.name == .darkAqua {
                return true
            }
        }
        return false
    }
}

extension ViewController {
    
    func startConnection(service: Server) {
        let connection = BonjourConnection(service: service.service)
        connection.onGestureReceived = { [weak self] gesture in
            self?.keyboard.simulate(gesture: gesture)
        }
        self.connection = connection
        connection.open()
    }
    
    func stopConnection() {
        connection?.close()
        connection = nil
    }
}

