using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;


public class scriptEnnemi : MonoBehaviour {
    public float speed;
    public bool loop;
    private float dirH, dirV;
    private Rigidbody2D character;
    private int iPoint;
	bool allergy = false;
    private List<Vector2> listPoint;
    private int sens;
    // Use this for initialization
    
    void Start () {
        character = this.GetComponent<Rigidbody2D>();
        iPoint = 1;
        sens = 1;
        listPoint = new List<Vector2>();
        for(int i = 0; i < this.transform.childCount-1; i++)
        {
            float x, y;
            x = this.transform.GetChild(i).transform.position.x;
            y = this.transform.GetChild(i).transform.position.y;
            listPoint.Add(new Vector2(x, y));
        }
        calculeDirection();
    }
	
	// Update is called once per frame
	void Update () {
		if (allergy || transform.childCount == 1)
			return;
        Vector2 movement = new Vector2(dirH,dirV);
        movement *= speed;
        character.AddForce(movement);
        Vector2 truePos = new Vector2(this.transform.position.x, this.transform.position.y);
        if (Mathf.Round(Vector2.Distance(truePos, listPoint[iPoint])*10)==0)
        {
            character.velocity = new Vector3(0, 0, 0);
            this.transform.position.Set(listPoint[iPoint].x,listPoint[iPoint].y,0);
            iPoint+=sens;
            if (loop && iPoint == listPoint.Count)
            {
                iPoint = iPoint % listPoint.Count;
            }
            else if(iPoint == listPoint.Count || iPoint < 0)
            {
                sens *= -1;
                iPoint+=sens*2;
            }
            calculeDirection();
        }
    }


    private void calculeDirection()
    {
		if (transform.childCount == 1)
			return;
        float deltaH = listPoint[iPoint].x - this.transform.position.x;
        float deltaV = listPoint[iPoint].y - this.transform.position.y;
        dirH = 0;
        dirV = 0;
        if (Mathf.Round(10 * deltaH) != 0)
        {
            dirH = deltaH / Mathf.Abs(deltaH);
        }
        if (Mathf.Round(deltaV * 10) != 0)
        {
            dirV = deltaV / Mathf.Abs(deltaV);
        }
        if (dirH == 1)
        {
            this.transform.rotation = Quaternion.AngleAxis(0, Vector3.forward);
        }
        else if (dirH == -1)
        {
            this.transform.rotation = Quaternion.AngleAxis(180, Vector3.forward);
        }
        if (dirV == 1)
        {
            this.transform.rotation = Quaternion.AngleAxis(90, Vector3.forward);
        }
        else if (dirV == -1)
        {
            this.transform.rotation = Quaternion.AngleAxis(270, Vector3.forward);
        }
    }

	public void toxines(){
			allergy = !allergy;
			transform.GetChild(transform.childCount-1).gameObject.SetActive(!transform.GetChild(transform.childCount-1).gameObject.activeSelf);
	}
}