//
//  Runner.swift
//
//  Copyright © 2020 Apple Inc. All rights reserved.
//


import SPCScene
import SpriteKit

public typealias RunnableScene = Scene & SceneAnimating

public class Runner : SceneAnimatingDelegate {
    static let defaultTransition = SKTransition.fade(with: .black, duration: 2.0)
    
    public var scenes: [RunnableScene]
    public var currentlyPresentedIndex = -1
    
    public init (_ toLoad: [RunnableScene]) {
        scenes = toLoad
        for var scene in scenes {
            scene.animationDelegate = self
        }
    }
    
    public func start() {
        guard let initialScene = scenes.first  else { return }
        currentlyPresentedIndex = 0
        present(scene: initialScene)
    }
    
    fileprivate func transition(for runnable: RunnableScene) -> SKTransition? {
        var transition = Runner.defaultTransition
        transition.pausesIncomingScene = false
        transition.pausesOutgoingScene = false
        
        if let trans = runnable.sceneTransition {
            transition = trans
        }
        return transition
    }
    
    public func present(scene runnable: RunnableScene) {
        let trans = transition(for: runnable)
        Canvas.present(scene: runnable, transition: trans)
        
        DispatchQueue.main.async {
            let elems = runnable.accessibilityElements
            UIAccessibility.post(notification: .layoutChanged, argument: runnable.axSceneElement!)
            runnable.sceneIsPresented()
        }
        
    }
    
    
    // MARK: - SceneAnimatingDelegate
    
    public func sceneDidLoad(_ scene: SceneAnimating) {
        
    }
    
    public func sceneDidFinishAnimations(_ scene: SceneAnimating) {
        scene.sceneWillDismiss()
        
        currentlyPresentedIndex = currentlyPresentedIndex + 1
        guard currentlyPresentedIndex < scenes.count else {
            // TODO: Run page completion
            return
        }
        
        present(scene: scenes[currentlyPresentedIndex])
    }
    
}
