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

public class PlayerActor : MonoBehaviour {
    public PlayerState PState;

    public GameObject ShipPrefab;
    public enum PlayerState
    {
        Normal
    }
    public bool CanFire
    {
        get { return Time.time - LastFireTime > TimeBetweenFire; }
    }

    public bool IsCharging
    {
        get; private set;
    }
    private float StartChargeTime = 0;
    public float MaxChargeTime;
    private GameObject ReticleRenderer;

    private float LastFireTime = -5;
    private float TimeBetweenFire = 1;

    private float LastTimeCrewLoaded = 0;
    private float TimeBetweenCrewLoad = .25f;

    public int PlayerNum
    {
        get
        {
            Controller c = this.GetComponent<Controller>();
            if (c) { return c.playernum; }
            else { return -1; }
        }
    }

    public float CurrentCharge
    {
        get
        {
            if (!this.IsCharging)
            {
                return 0f;
            }
            return Mathf.Clamp(Time.time - this.StartChargeTime, 0, MaxChargeTime) / MaxChargeTime;
        }
    }

    public float charge;
    public float FiringAngle;

    public Color PlayerColor
    {
        get
        {
            return GameLogic.PlayerColors[PlayerNum - 1];
        }
    }

    private Vector3 GetFiringAngle()
    {
        // return Camera.main.ScreenToWorldPoint(Input.mousePosition) - this.transform.position;

        Controller c = this.GetComponent<Controller>();
        if (c)
        {
            float xaxis = c.h_axis;
            float yaxis = c.v_axis;
            Vector3 v = new Vector3(xaxis, yaxis, 0);
            return v.normalized;
        }
        else { return Vector3.zero; }
    }
    public Controller controller
    {
        get
        {
            return this.GetComponent<Controller>();
        }
    }

    void Start()
    {
        this.IsCharging = false;
    }
    
    private void OnTriggerEnter2D(Collider2D collision)
    {
    }
    private void OnTriggerExit2D(Collider2D collision)
    {
    }

    private void Update()
    {

        foreach (Transform sr in this.GetComponentsInChildren<Transform>())
        {
            if (sr.name == "ReticleContainer")
            {
                this.ReticleRenderer = sr.gameObject;
                foreach (SpriteRenderer img in this.ReticleRenderer.GetComponentsInChildren<SpriteRenderer>())
                {
                    img.color = PlayerColor;
                }
                Image chargeMeter = sr.Find("ChargeMeter").gameObject.GetComponent<Image>();
                chargeMeter.color = PlayerColor;
                chargeMeter.fillAmount = CurrentCharge;
            }
        }
    }

    // Update is called once per frame
    void FixedUpdate () {
        charge = CurrentCharge;

        Controller c = this.GetComponent<Controller>();
        
        this.FiringAngle -= c.h_axis*2f;

        ShipCrewLoadout crewLoadout = this.GetComponentInChildren<ShipCrewLoadout>();
        //crewLoadout.CanLaunch = this.CanFire;

        if (this.CanFire && !this.IsCharging)
        {
            if (Time.time - LastTimeCrewLoaded > TimeBetweenCrewLoad)
            {
                if (c.y_button || c.x_button || c.b_button)
                {
                    Crew.CrewType ct = Crew.CrewType.Dog;
                    if (c.y_button) { ct = Crew.CrewType.Dog; }
                    else if (c.x_button) { ct = Crew.CrewType.Cat; }
                    else if (c.b_button) { ct = Crew.CrewType.Frog; }
                    crewLoadout.ToggleCrewType(ct);
                    LastTimeCrewLoaded = Time.time;
                }
            }
        }

        if (this.IsCharging)
        {
            if (!c.a_button)
            {
                // Fire!
                float firePower = CurrentCharge;

                GameObject ship = Instantiate(ShipPrefab);
                SpriteRenderer[] shipSpriteRenderers = ship.gameObject.GetComponentsInChildren<SpriteRenderer>();
                foreach (SpriteRenderer sr in shipSpriteRenderers)
                {
                    sr.color = PlayerColor;
                }
                ShipController oc = ship.GetComponent<ShipController>();
                CrewSpawner crewSpawner = FindObjectOfType<CrewSpawner>();
                foreach (Crew.CrewType ct in crewLoadout.LoadedCrewTypes)
                {
                    Crew crew = crewSpawner.SpawnCrew(ct, PlayerNum);
                    crew.TransferTo(oc.gameObject);
                    //foreach (Crew crew in this.gameObject.transform.parent.GetComponentsInChildren<Crew>())
                    //{
                    //    if (crew.CType == ct)
                    //    {
                    //        crew.TransferTo(oc.gameObject);
                    //        break;
                    //    }
                    //}
                }

                oc.percentPower = CurrentCharge;
                oc.tiltAngle = this.FiringAngle;
                oc.Owner = this;

                Vector3 startPos = this.ReticleRenderer.GetComponentInChildren<SpriteRenderer>().transform.position;
                oc.X = startPos.x * -1f;
                oc.Y = startPos.y * -.8f;

                this.LastFireTime = Time.time;
                crewLoadout.ClearLoadedCrew();

                this.IsCharging = false;
            }
        }
        else if (!this.IsCharging && this.CanFire && c.a_button)
        {
            // Start Charge
            this.IsCharging = true;
            this.StartChargeTime = Time.time;
        }

        //if(c)
        //{
        //    if (c.a_button && this.CanFire)
        //    {
                
        //    }

        //    if (!this.CanFire)
        //    {
        //        this.IsCharging = false;
        //    }

        //    if (this.CanFire && c.a_button)
        //    {
        //        //CanFire cf = this.GetComponent<CanFire>();
        //        if (!this.IsCharging)
        //        {
        //            this.IsCharging = true;
        //            this.StartChargeTime = Time.time;
        //        }
        //    }
        //    else
        //    {
        //        if (this.IsCharging)
        //        {
        //            this.IsCharging = false;
        //            float firePower = CurrentCharge;

        //            Instantiate(ShipPrefab);
        //            this.LastFireTime = Time.time;

        //            //CanFire cf = this.GetComponent<CanFire>();
        //            //if (cf)
        //            //{
        //            //    cf.Fire(GetFiringAngle() * firePower);
        //            //}
        //        }
        //    }

        //    //if(this.IsCharging)
        //    //{
        //    //    c.Vibrate(Controller.MediumVibrationFactor, Controller.MediumVibrationFactor);
        //    //}
        //}
    }

    float VectorToAngle(Vector2 vec)
    {
        return Mathf.Atan2(vec.y, vec.x) * 180f / Mathf.PI;
    }

    public Vector3 RotatePointAroundPivot(Vector3 point, Vector3 pivot, Vector3 angles)
    {
        return Quaternion.Euler(angles) * (point - pivot) + pivot;
    }

    void LateUpdate()
    {
        if (this.ReticleRenderer)
        {
            //float ang = this.VectorToAngle(this.GetFiringAngle());
            //Vector2 a = this.GetFiringAngle();
            //this.ReticleRenderer.GetComponentInChildren<SpriteRenderer>().gameObject.SetActive(a.magnitude >= .001f);

            //float ang = Vector2.Angle(Vector2.up, a);
            //Vector3 cross = Vector3.Cross(Vector2.up, a);

            //if (cross.z > 0)
            //{
            //    ang = 360 - ang;
            //}

            //Vector3 currentRotation = this.ReticleRenderer.transform.localEulerAngles;
            //currentRotation.z = ang - 90;
            //this.ReticleRenderer.transform.rotation = RotatePointAroundPivot(
            //    new Vector3(0, 3, 0),
            //    Vector3.zero,
            //    currentRotation);//Quaternion.AngleAxis(ang, -1*Vector3.forward);

            float ang = this.FiringAngle;
            this.ReticleRenderer.transform.rotation = Quaternion.AngleAxis(-1*ang+90, -1 * Vector3.forward * 3);
        }

    }
}
