//
//  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!
    var isMoveTouch = false
    var currentDraggedBasePos = CGPoint()
    var currentDraggedBase : Base?
    
    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 touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        guard let touch = touches.first else {
            return
        }

        let touchLocation = touch.location(in: self)

		if isMoveTouch{
			isMoveTouch = false
            currentDraggedBase!.component(ofType: DefaultBaseComponent.self)?.spriteNode.position = currentDraggedBasePos
            currentDraggedBase!.component(ofType: TeamComponent.self)?.fire.position = currentDraggedBasePos

			for base in currentDraggedBase!.adjacencyList {
				if atPoint(touchLocation) == base.component(ofType: DefaultBaseComponent.self)?.spriteNode {
					// TODO: change interaction based on collision instead of touchlocation

					if !(entityManager.getTeamByBase(base: currentDraggedBase!) == entityManager.getTeamByBase(base: base)){
						entityManager.add(Modal(modaltype: .BaseAttack,
												base: currentDraggedBase!,
												anchorPoint: CGPoint(x: self.size.width / 2 , y: self.size.height / 2)))
						entityManager.update((currentDraggedBase?.attackBase(base: base, units: 100))!)
					}else {
						entityManager.add(Modal(modaltype: .BaseAttack,
												base: currentDraggedBase!,
												anchorPoint: CGPoint(x: self.size.width / 2 , y: self.size.height / 2)))
					}
	
				}
			}
		}
        else {
            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 touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        guard let touch = touches.first else {
            return
        }
        let touchLocation = touch.location(in: self)

		for child in children {
			if atPoint(touchLocation) == child {
				child.touchesMoved(touches, with: event)
			}
		}

		for e in entityManager.entities{
			if let body = e.component(ofType: ModalContentComponent.self)?.body{
				body.text = "Schicke \(  ((e.component(ofType: SliderComponent.self)?.sliderNode.getValue ?? 0) * CGFloat((e as! Modal).unitCount)).rounded(.up)) Einheiten "
			}		}

        let bases = entityManager.getBasesByTeam(for: .team1)

        for base in bases {
            if atPoint(touchLocation) == base.component(ofType: DefaultBaseComponent.self)?.spriteNode{
                if !isMoveTouch {
                    currentDraggedBasePos = base.component(ofType: DefaultBaseComponent.self)!.spriteNode.position
                    currentDraggedBase = base
                }
                isMoveTouch = true

                base.component(ofType: DefaultBaseComponent.self)?.spriteNode.position = touchLocation
                base.component(ofType: TeamComponent.self)?.fire.position = touchLocation
                for adjacencyBase in base.adjacencyList {
                    let node =  adjacencyBase.component(ofType: DefaultBaseComponent.self)?.spriteNode
                    node?.run(SKAction.sequence([
                        SKAction.resize(byWidth: 2, height: 2, duration: 0.5),
                        SKAction.resize(byWidth: -2, height: -2, duration: 0.5)
                    ]))
                }
            }
        }
    }
    
    override func update(_ currentTime: TimeInterval) {
        entityManager.getBackground()?.update(deltaTime: currentTime)
        entityManager.getHUD()?.component(ofType: TimerComponent.self)?.update()
    }
}
