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

public class HeadController : MonoBehaviour {
    private BaseCell head;
    private Vector2 centerOfMass;
    [HideInInspector]
    public List<BaseCell> openCells;

    public int nutrition;
    public int cellCount;


	// Use this for initialization
	void Awake () {
        head = GetComponent<BaseCell>();
	    head.headController = this;
        centerOfMass = transform.position;
        RecreateOpenConnectionList();
        head.onStructureChange = RecreateOpenConnectionList;
	}
	
	// Update is called once per frame
	void FixedUpdate () {
        CalculateCenterOfMass();
	}

    void RecreateOpenConnectionList()
    {
        openCells = new List<BaseCell>();
        head.GetAllOpenCells(ref openCells);
    }

    public void MoveTowards(Vector2 dir)
    {
        head.MoveTowards(dir);
    }

    public void RotateTowards(float target)
    {
        var angleDiff = Mathf.DeltaAngle(transform.eulerAngles.z, target+180);
        head.Rotate(centerOfMass, angleDiff/45f);
    }

    void CalculateCenterOfMass()
    {
        var fullMass = 0f;
        cellCount = 0;
        var allPositions = Vector2.zero;
        head.CalculatePositionsAndMass(ref fullMass,ref allPositions, ref cellCount);
        centerOfMass = (allPositions/fullMass);
    }

    public void AddNutrition()
    {
        nutrition++;
    }

    public void UseNutrition()
    {
        nutrition--;
    }

    public bool HasNutrition()
    {
        return nutrition > 0;
    }
}
