//
//  GameScene.swift
//  GoldWars
//
//  Created by Aldin Duraki on 18.04.20.
//  Copyright © 2020 SP2. All rights reserved.
//

import SpriteKit
import GameplayKit

class GameScene: SKScene{
    
    var entityManager: EntityManager!
    
    override func sceneDidLoad() {
        entityManager = EntityManager(scene: self)
        entityManager.add(HUD(size: self.size))
        entityManager.add(Background(size: self.size))
        initMap()
    }
    

    
    func initMap() {
        MapFactory(scene: self, entityManager: self.entityManager).loadMap(playerCount: 2)
    }
    
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        guard let touch = touches.first else {
            return
        }
        
        let touchLocation = touch.location(in: self)
        
        for entity in entityManager.entities {
            
            let spriteNode = entity.component(ofType: DefaultBaseComponent.self)?.spriteNode
            
            if entityManager.isModal && entity.isMember(of: Modal.self) {
                entityManager.remove(entity)
                for child in self.children {
                    if(child.name != "fire"){
                        child.alpha = 1
                    }
                }
                
            }
            
            if atPoint(touchLocation) == spriteNode && !entityManager.isModal {
                spriteNode?.touchesBegan(touches, with: event)
                if !entityManager.isModal {
                    for child in self.children {
                        if(child.name != "fire"){
                            child.alpha = 0.3
                        }
                        
                    }
                    entityManager.add(Modal(modaltype: .BaseDetails,
                                            base: entity as! Base,
                                            anchorPoint: CGPoint(x: self.size.width / 2 , y: self.size.height / 2)))
                }
            }
        }
    }
    

    
    override func update(_ currentTime: TimeInterval) {
        entityManager.getBackground()?.update(deltaTime: currentTime)
    }
}
