﻿using UnityEngine;
using System.Collections.Generic;

namespace Nostalgia.Example
{
	[AddScriptMenu("Example/Breakable")]
	public sealed class BreakableTile : TileComponent, ITileCollisionReceiver
	{
		public GameObject[] spawnObjects;

		void ITileCollisionReceiver.OnCollisionEnter(CollisionTile collisionTile)
		{
			if (!collisionTile.collider.CompareTag("Player"))
			{
				return;
			}

			Map map = collisionTile.map;

			for (int cellIndex = 0; cellIndex < collisionTile.collisionCellCount; cellIndex++)
			{
				CollisionCell collisionCell = collisionTile.GetCollisionCell(cellIndex);
				Cell cell = collisionCell.cell;

				Vector3 pos = map.MapPointToWorldPoint(cell.position);

				int contactLength = collisionCell.contactCount;
				for (int contactIndex = 0; contactIndex < contactLength; contactIndex++)
				{
					ContactPoint2D contact = collisionCell.GetContact(contactIndex);
					if (contact.normal.y > 0.5f)
					{
						foreach (GameObject spawnObject in spawnObjects)
						{
							GameObject broken = Instantiate(spawnObject, pos, Quaternion.identity) as GameObject;
							broken.transform.localScale = map.transform.lossyScale;
						}

						map.RemoveTile(cell.position, true);

						Rigidbody2D rigidbody = collisionTile.rigidbody;
						if (rigidbody != null)
						{
							Vector2 velocity = Physics2DUtility.GetLinearVelocity(rigidbody);
							velocity.y = 0.0f;
							Physics2DUtility.SetLinearVelocity(rigidbody, velocity);
						}

						break;
					}
				}
			}
		}

		void ITileCollisionReceiver.OnCollisionExit(CollisionTile collisionTile)
		{
		}

		void ITileCollisionReceiver.OnCollisionStay(CollisionTile collisionTile)
		{
		}
	}
}