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

public class SlotManager : MonoBehaviour
{
	public int id;
	public int tipo;
	public bool isRing;
	public AudioClip jackplug, jackunplug;
	public AudioSource jackIn;
	public MeshRenderer slotSpiaRenderer;
	public Material spiaSpenta, spiaAccesa, spiaInUso, spiaConnessa;
	private Vector3 rotPos = new Vector3(90,0,-90), resetRot = new Vector3(0,0,-90);
	private Vector3 resetPos;
	private JackManager myJack;
	private bool isCorrectJack;

	public void JackAttach(JackManager jMan, Vector3 orgPos)
	{
		jackIn.clip = jackplug;
		jackIn.Play();
		resetPos = orgPos;
		myJack = jMan;
		myJack.trn.position = transform.position;
		myJack.trn.eulerAngles = rotPos;

		ConnectSlot();
		myJack.ConnectJack();

		if (jMan.tipo == tipo && jMan.slotDest == id)
		{
			isCorrectJack = true;

			GameManager.GM.SlotActive(this);
		}
		else
		{
			isCorrectJack = false;
		}
	}

	public void RingSlot()
	{
		isRing = true;
		slotSpiaRenderer.material = spiaAccesa;
	}

	public void ConnectSlot()
	{
		slotSpiaRenderer.material = spiaConnessa;
	}

	public void UseSlot()
	{
		slotSpiaRenderer.material = spiaInUso;
		myJack.UseJack();
	}

	public void OffSlot()
	{
		slotSpiaRenderer.material = spiaSpenta;
	}

	public void NomoreRing()
	{
		isRing = false;
	}

	public void RemoveJack()
	{
		isCorrectJack = false;
	}

	public void OnMouseDown()
	{
		if (!isCorrectJack)
		{
			RemoveAll();
		}
	}

	public void RemoveAll()
	{
		if (myJack)
		{
			jackIn.clip = jackunplug;
			jackIn.Play();
			myJack.trn.position = resetPos;
			myJack.trn.eulerAngles = resetRot;
			myJack.trn.GetComponent<Collider>().enabled = true;

			if (isRing)
			{
				RingSlot();
			}
			else
			{
				OffSlot();
			}

			if (myJack.isRing)
			{
				myJack.RingJack(myJack.slotDest);
			}
			else
			{
				myJack.OffJack();
			}

			myJack = null;
			GameManager.GM.RemoveSlot(this);
		}
	}
}
