﻿using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.Serialization;

public class Food : MonoBehaviour {

	public GameObject foodPrefab;
	public Transform rightWall;
	public Transform leftWall;
	public Transform topWall;
	public Transform bottomWall;

	// Use this for initialization
	private void Start () {
		SpawnFood();
	}


	int _count = 0;

	public void SpawnFood() {
		var x = (int)Random.Range (leftWall.position.x, rightWall.position.x);
		var y = (int)Random.Range (bottomWall.position.y, topWall.position.y);

		/* if (count % 2 == 0) {
			x = -5;
			y = 0;
		}

		if (count %2 != 0) {
			Masken masken = GetComponent<Masken> (); 
			RectTransform[] rectTransM = masken.GetRectTransforms ();
			if (rectTransM.Length > 1) {
				x = (int)rectTransM [1].localPosition.x;
				y = (int)rectTransM [1].localPosition.y;

				Debug.Log ("Resetting " + x + " " + y);
			}
		} */

		_count++;
			
		var food = Instantiate (foodPrefab, new Vector2 (x, y), Quaternion.identity);
		// if (CheckOverlapsWithScore (food) || CheckOverlapsWithMasken (food)) {
		if (CheckOverlapsWithMasken (food)) {
			Destroy (food);
			SpawnFood ();
		} 

	}

	private bool CheckOverlapsWithScore(GameObject food) {
		var rectTransF = food.GetComponent<RectTransform> (); 
		var score = GetComponent<Score> (); 
		// score = null; 
		if (!score) {
			return false;
		}
		var rectTransS = score.GetRectTransform ();

		// The position is offset with a half for some reason I cannot find. Just add 0.5f to x to the localposition. 
		var localPosition = rectTransF.localPosition;
		var rect = rectTransF.rect;
		var position = rectTransS.localPosition;
		var rect1 = rectTransS.rect;
		
		var rectF = new Rect(localPosition.x+0.5f, localPosition.y, rect.width, rect.height);
		var rectS = new Rect(position.x, position.y, rect1.width, rect1.height);

		var overlaps = rectF.Overlaps(rectS);

		return overlaps;
	}

	private bool CheckOverlapsWithMasken(GameObject food) {
		var rectTransF = food.GetComponent<RectTransform> (); 
		var masken = GetComponent<Masken> (); 
		if (!masken) {
			return false;
		}
		var rectTransM = masken.GetRectTransforms ();

		for (var i = 0; i < rectTransM.Length; i++) {
			if (rectTransM[i]) {
				if (CheckOverlaps (rectTransF, rectTransM[i])) {
					Debug.Log ("Masken " + i + " overlaps.");
					return true; 
				}
			}
		}
		return false; 
	}

	static bool CheckOverlaps(RectTransform rectTrans1, RectTransform rectTrans2) {
		// The position is offset with a half for some reason I cannot find. Just add 0.5f to x to the local position. 
		var localPosition = rectTrans1.localPosition;
		var rect = rectTrans1.rect;
		var position = rectTrans2.localPosition;
		var rect3 = rectTrans2.rect;
		
		var rect1 = new Rect(localPosition.x+0.5f, localPosition.y, rect.width, rect.height);
		var rect2 = new Rect(position.x, position.y, rect3.width, rect3.height);

		return rect1.Overlaps(rect2);
	}

}
