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

public class InteractionManager : MonoBehaviour
{
	public LayerMask interactableMask;
	public InteractionTypes currentInteraction;

	private void Update()
	{
		if (!GameManager.Interactable)
		{
			currentInteraction = InteractionTypes.None;
		}

		if (Input.GetMouseButtonUp(0))
		{
			switch (currentInteraction)
			{
				case InteractionTypes.Repair:
					Repair();
					break;
				case InteractionTypes.Reap:
					Reap();
					break;
			}
		}
	}

	private void Reap()
	{
		Vector3 mousePosition = Input.mousePosition;
		Vector3 origin = Camera.main.ScreenToWorldPoint(mousePosition);
		Vector3 direction = Camera.main.transform.forward;
		Ray ray = new Ray(origin, direction);
		RaycastHit[] hits = Physics.RaycastAll(ray, 1000f, interactableMask);

		foreach (RaycastHit hit in hits)
		{
			FactionInfo factionInfo = hit.transform.GetComponent<FactionInfo>();
			if (factionInfo != null && factionInfo.Faction == Factions.Player)
			{
				Attackable attackable = hit.transform.GetComponent<Attackable>();
				if (attackable != null)
				{
					attackable.Reap();
				}
			}
		}
	}

	private void Repair()
	{
		Vector3 mousePosition = Input.mousePosition;
		Vector3 origin = Camera.main.ScreenToWorldPoint(mousePosition);
		Vector3 direction = Camera.main.transform.forward;
		Ray ray = new Ray(origin, direction);
		RaycastHit[] hits = Physics.RaycastAll(ray, 1000f, interactableMask);

		foreach (RaycastHit hit in hits)
		{
			FactionInfo factionInfo = hit.transform.GetComponent<FactionInfo>();
			if (factionInfo != null && factionInfo.Faction == Factions.Player)
			{
				Attackable attackable = hit.transform.GetComponent<Attackable>();
				if (attackable != null)
				{
					attackable.Repair();
				}
			}
		}
	}
}

public enum InteractionTypes : short
{
    None,
    Place,
    Repair,
    Reap
};
