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

public class LDWeaponBeam : TM_Weapon
{
    public LDGameActor myOwningActor;
    public GameObject Prefab_BeamProjectile;
    public GameObject beamAnchorObject;
    public int MaxBeams = 5;
    public float BeamDPS;

    private List<LDBeamProjectile> myBeemz;

    public List<LDCombatComponent> listCombatTargets;

    private bool bBeamsFiring;

    private GameManager theGame;

    public AudioClip clip_BeamHit;


	// Use this for initialization
	void Start () 
    {
        theGame = GameManager.GetGame();

        myBeemz = new List<LDBeamProjectile>();
        for (int t = 0; t < MaxBeams; t++)
        {
            GameObject go = Instantiate(Prefab_BeamProjectile) as GameObject;
            go.transform.parent = transform;
            myBeemz.Add( go.GetComponent<LDBeamProjectile>());
        }
	}
	
	// Update is called once per frame
	void Update () 
    {
        if (theGame.GetGameState() != EGameState.gameplay)
        {
            return;
        }

        if (theGame.thePlayer.myRewiredPlayer.GetAxis2D("AimHorizontal", "AimVertical").sqrMagnitude > 0.1f * 0.1f)
        {
            listCombatTargets = theGame.theAIManager.GetTargetsInArea(5, myOwningActor.Faction, 12f, myOwningActor.GetTargetingPosition(), true, transform.up, 35f);

            //match beems to targets
            for (int iBeamIdx = 0; iBeamIdx < MaxBeams; iBeamIdx++)
            {
                if (iBeamIdx < listCombatTargets.Count)
                {
                    LDGameActor targetActor = listCombatTargets[iBeamIdx].myOwningActor;
                    myBeemz[iBeamIdx].EnableBeam(this, targetActor);
                    targetActor.TakeDamage(BeamDPS * Time.deltaTime, myOwningActor);
                    TM_AudioManager.PlayUIClip(clip_BeamHit);
                }
                else
                {
                    myBeemz[iBeamIdx].DisableBeam();
                }
            }
        }

        //turn off all beemz if not firing
        else
        {
            for (int t = 0; t < MaxBeams && t < listCombatTargets.Count; t++)
            {
                myBeemz[t].DisableBeam();
            }
        }

        /*
        if (listCombatTargets != null)
        {
            for (int t = 0; t < listCombatTargets.Count; t++)
            {
                Debug.DrawLine(transform.position, listCombatTargets[t].gameObject.transform.position, Color.red, 0.05f, false);
            }
        }
        */
	}

    public Vector3 GetBeamAnchorScreenPosition()
    {
        return beamAnchorObject.transform.position;

    }
}
