﻿using UnityEngine;

public class Attackable : MonoBehaviour
{
	[SerializeField] private float health = 10;
	[SerializeField] private float maxHealth = 10;

	private HarvestInfo harvestInfo;

	private void Start()
	{
		health = maxHealth;
		harvestInfo = GetComponent<HarvestInfo>();
	}

	private void Update()
	{
	}

	public void Repair()
	{
		if (harvestInfo == null)
		{
			throw new System.Exception("Cannot Repair; No HarvestInfo found");
		}

		float repairPercentage = 1 - health / maxHealth;
		float repairCost = harvestInfo.GetBaseValue() * harvestInfo.GetCostMultiplier() * repairPercentage;

		if (repairCost < GameManager.Harvest)
		{
			GameManager.Sow(repairCost);
			health = maxHealth;
		}
	}

	public void TakeDamage(float damage)
	{
		health -= damage;

		if (health <= 0)
		{
			health = 0;
			Reap();
		}
	}

	private void OnDestroy()
	{
		if (!GameManager.IsQuitting && harvestInfo != null)
		{
			GameObject reapEffectGameObject = Instantiate(GameManager.ReapEffectPrefab, transform.position, transform.rotation);
			Harvest harvest = reapEffectGameObject.GetComponent<Harvest>();
			if (harvest == null)
			{
				throw new System.Exception("ReapEffect game object does not have Harvest component");
			}
			harvest.value = harvestInfo.GetValue();
		}
	}

	public void Reap()
	{
		Destroy(gameObject);
	}

	public float GetHealthPercentage()
	{
		return health / maxHealth;
	}

	public float GetMaxHealth()
	{
		return maxHealth;
	}
}

[System.Flags]
public enum Factions : short
{
	None = 0,
	Player = 1,
	Fightbois = 2,
	Shootbois = 4,
	Splodbois = 8
};
