extends Node2D

export var  lightning_color = Color()

var speed = 120.0
var move = false
var sleep = true
var point_c = Vector2()

signal shake_complete

onready var lightning_strike_effect_scene = load("res://scenes/effects/lightning_strike_effect.tscn")

func _process(delta):
	if move:
		position.x -= speed * delta
			
func lightning():
	if sleep:
		return
	move = false
	point_c = $ray.get_collision_point() - global_position
	shake()
	$Area2D.monitoring = true
	var _player = Audio.play_sound("electric_zap", true)
	var lightning_strike_effect = lightning_strike_effect_scene.instance()
	lightning_strike_effect.global_position = point_c + global_position
	get_parent().add_child(lightning_strike_effect)
	yield(self, "shake_complete")
	_player.stop()
	move = true
	$Area2D.monitoring = false
	$bullet_time.start()
	yield($bullet_time,"timeout")
	lightning()
	
func shake():
	for i in 30:
		var _offset = Vector2(rand_range(-8, 8),  rand_range(-8, 8)) 
		$Sprite.offset = _offset
		yield(get_tree().create_timer(0.04),"timeout")
		update()
	emit_signal("shake_complete")
	
func _draw():
	if !move: 
		var point_a = Vector2(0,0)
		var point_b = Vector2(0,0)
		for i in 4:
			if i < 3:
				point_b = point_a + Vector2(rand_range(-64, 64), point_c.y/4)
			else:
				point_b = point_c + Vector2(rand_range(-64, 64),0)
			draw_line(point_a, point_b, lightning_color, 8, true)
			point_a = point_b
			
func _on_screen_entered():
	sleep = false
	move = true
	yield(get_tree().create_timer(1.8),"timeout")
	lightning()
	
func _on_screen_exited():
	sleep = true
	move = false
	
func _on_area_body_entered(body):
	body.apply_damage(1, "burning")

func _ready():
	$Area2D.connect("body_entered", self, "_on_area_body_entered")
	$VisibilityEnabler2D.connect("screen_entered", self, "_on_screen_entered")
	$VisibilityEnabler2D.connect("screen_exited", self, "_on_screen_exited")
