//
//  TimerComponent.swift
//  GoldWars
//
//  Created by Daniel Steckert on 05.05.20.
//  Copyright © 2020 SP2. All rights reserved.
//

import GameplayKit

class TimerComponent: GKComponent {

    let labelNode    :SKLabelNode
    var endTime      :Date!
    var duration     :Double

     init(text: String, anchorPoint: CGPoint, duration: TimeInterval) {
        self.labelNode = SKLabelNode(text: text)
        self.labelNode.fontColor = UIColor.black
        self.labelNode.fontSize = CGFloat(45)
        self.labelNode.position = CGPoint(x: anchorPoint.x, y: anchorPoint.y - 15)
        self.duration = duration + 1
        super.init()
        startWithDuration(duration: self.duration)
    }
    
    func startWithDuration(duration: TimeInterval){
        endTime = Date().addingTimeInterval(duration)
    }
    
    func timeLeft() -> Int {
        let remainingSeconds =  Int(endTime.timeIntervalSince(Date()))
        if(remainingSeconds < 0 ){
            startWithDuration(duration: duration)
        }
        return remainingSeconds
    }
    
    func isFinished() -> Bool {
        return timeLeft() == 0
    }
    
    func update() {
        self.labelNode.text = String(timeLeft())
        
        if(isFinished()){
            self.labelNode.text = "Synching"
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

