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

public class Clicker : MonoBehaviour
{
    public Camera cam;
    public float raycastLength = 5;
    public Vector2 rayOrgin = Vector2.zero;
    public string rayMaskLayer = "";
    public MassSoundSubscriber sound;
    public string grabSound;
    public string missSound;


    private int rayMask;

    private bool leftArmAvailable = true;
    private bool rightArmAvailable = true;

    public Animator leftArm;
    public Animator rightArm;

    // Start is called before the first frame update
    void Start()
    {
        if (cam == null)
        {
            cam = Camera.main;
        }

        if (sound == null)
        {
            sound = GetComponent<MassSoundSubscriber>();
        }

        var layerId = LayerMask.NameToLayer(rayMaskLayer);
        rayMask = 1 << layerId;
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButtonDown(0) && leftArmAvailable)
        {
            leftArm.SetTrigger("Grab");
            leftArmAvailable = false;
        }        
        
        if (Input.GetMouseButtonDown(1) && rightArmAvailable)
        {
            rightArm.SetTrigger("Grab");
            rightArmAvailable = false;

        }

    }

//****** Animation driven events

    public void grabAttempt(bool leftArmOriented)
    {
        Ray ray = cam.ScreenPointToRay(new Vector3(Screen.width / 2.0f, Screen.height / 2.0f));
        var raycastHits = Physics.RaycastAll(ray, raycastLength, rayMask);
        foreach (var hit in raycastHits)
        {
            var other = hit.collider.gameObject.GetComponent<IPokeable>();
            if (other != null)
            {
                other.sendMessage("grabbed");
                if(leftArmOriented) leftArm.SetTrigger("Grabbed"); else rightArm.SetTrigger("Grabbed");
                maybeCallSound(grabSound);
            }
            else
            {
                maybeCallSound(missSound);
            }
        }
    }

    public void armFinishedGrab(bool leftArmSet)
    {
        if (leftArmSet)
        {
            leftArmAvailable = true;
        }
        else
        {
            rightArmAvailable = true;

        }

    }

    private void maybeCallSound(string soundName)
    {
        if (sound != null)
        {
            sound.playSound(this.transform.position, soundName);
        }
    }
}