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

import UIKit
import AVFoundation

public protocol CameraFlashable {
    var shouldContinueCameraSounds: Bool { get set }
}

var audioPlayer: AVAudioPlayer?

public func animateFlash(imageView: UIImageView, in cameraFlashable: CameraFlashable, delay: TimeInterval, playSound shouldPlaySound: Bool, completion: @escaping (() -> Void)) {
    let addedDelay: TimeInterval = 0.5
    let scaledTransform = CGAffineTransform.identity.scaledBy(x: 0.7, y: 0.7)
    
    UIView.animate(withDuration: 0.4, delay: delay + addedDelay, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.0, options: .curveLinear, animations: {
        imageView.transform = CGAffineTransform.identity
        imageView.alpha = 1.0
    }) { _ in
        UIView.animate(withDuration: 0.2, delay: 0.0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.0, options: .curveLinear, animations: {
            imageView.transform = scaledTransform
            imageView.alpha = 0.0
        }, completion: { _ in
            completion()
        })
    }
    

    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + delay) {
        if shouldPlaySound && cameraFlashable.shouldContinueCameraSounds {
            guard let url = Bundle.main.url(forResource: "cameraShutterClick", withExtension: "m4a") else { return }
            do {
                if audioPlayer == nil {
                    audioPlayer = try AVAudioPlayer(contentsOf: url)
                }
                audioPlayer?.volume = 0.8
                audioPlayer?.play()
            } catch {}
        }
    }
}

public func animateFlash(imageView: UIImageView, in cameraFlashable: CameraFlashable, delays: [TimeInterval], playSound shouldPlaySound: Bool) {
    if let delay = delays.first {
        animateFlash(imageView: imageView, in: cameraFlashable, delay: delay, playSound: shouldPlaySound) {
            animateFlash(imageView: imageView, in: cameraFlashable, delays: Array(delays.dropFirst()), playSound: shouldPlaySound)
        }
    }
}
