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


import SpriteKit
import SPCScene
import Canvas

public class Loading : Scene, SceneAnimating {
    static let chestIdentifier = "LoadingScreen_1024-chest-%02d"
    static let scrollIdentifier = "LoadingScreen_1024-scroll-%02d"
    
    var background: Graphic
    var identifiers: String
    
    public init(with: Hut.HeroContents) {
        identifiers = (with == .scrollChest) ? Loading.chestIdentifier : Loading.scrollIdentifier
        
        let img = UIImage(named: String(format: identifiers, 1))!
        background = Graphic(image: Image(with: img), name: "Loading background")
        
        super.init(size: Scene.sceneSize)
        self.place(background, at: Point.center)
        
        let transition = SKTransition.fade(with: .black, duration: 0.5)
        transition.pausesIncomingScene = true
        transition.pausesOutgoingScene = false
        sceneTransition = transition
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - SceneAnimating
    
    public var sceneTransition: SKTransition?
    public var animationDelegate: SceneAnimatingDelegate?
    public var loadingDescription: String? {
        didSet {
            enableAccessibility(label: loadingDescription!)
        }
    }
    
    public func sceneIsPresented() {
        var bgs: [Image] = []
        var index = 1
        while index < 23 {
            let path = String(format: identifiers, index)
            if let img = UIImage(named: path) {
                bgs.append(Image(with: img))
            }
            index += 1
        }
        background.animate(with: bgs, fps: 10, loop: false)
        background.run(SKAction.wait(forDuration: 2.3)) {
            self.animationDelegate?.sceneDidFinishAnimations(self)
        }
    }
    
    public func sceneWillDismiss() {
        
    }
}
