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

public class IdolController : MonoBehaviour
{

    public float walkspeed = 6.0f;
    private float slidespeed = 0.0f;
    private float speed = 0f;
    private Vector3 moveDir;
    private Vector2 faceDir;
    [HideInInspector]
    public bool isGrab = false;
    private Rigidbody rigidBody;
    private string horizontalControl = "";
    private string verticalControl = "";
    private string fire1Control = "";
    private string fire2Control = "";
    public float currentControl = 1;
    private float pushBack = 8f;
    [HideInInspector]
    public List<Transform> fanFollowers;

    private Animator animator;
    //animation states - the values in the animator conditions
    private const int STATE_IDLE = 0;
    private const int STATE_WALK = 1;
    private const int STATE_HIT = 2;
    private const int STATE_CHARGE = 3;
    private const int STATE_CHARGE2 = 4;
    private int _currentAnimationState = STATE_IDLE;
    private SpriteRenderer spriteRender;
    private bool isGrounded = false;
    private GameObject globalObject;

    // Use this for initialization
    void Start()
    {
        globalObject = GameObject.Find("GlobalObject");
        spriteRender = GetComponent<SpriteRenderer>();
        animator = this.GetComponent<Animator>();
        rigidBody = GetComponent<Rigidbody>();
        faceDir.x = 1f;
        if (currentControl == 1)
        {
            //selectedIdol(StaticPref.player1Choice);
            //selectedIdol(PlayerPrefs.GetInt("player1Choice"));
            selectedIdol(globalObject.GetComponent<GlobalScript>().player1Choice);
            horizontalControl = "P1_horizontal";
            verticalControl = "P1_vertical";
            fire1Control = "P1_fire1";
            fire2Control = "P1_fire2";
        }
        else
        {
            //selectedIdol(StaticPref.player2Choice);
            //selectedIdol(PlayerPrefs.GetInt("player2Choice"));
            selectedIdol(globalObject.GetComponent<GlobalScript>().player2Choice);
            horizontalControl = "P2_horizontal";
            verticalControl = "P2_vertical";
            fire1Control = "P2_fire1";
            fire2Control = "P2_fire2";
        }
    }

    // Update is called once per frame
    void Update()
    {
        if (!isGrab)
        {
            moveDir = new Vector3(Input.GetAxisRaw(horizontalControl), 0, Input.GetAxisRaw(verticalControl)).normalized;
        }
        else
        {
            moveDir = new Vector3(faceDir.x, 0, faceDir.y).normalized;
        }
    }

   private void selectedIdol(int choice)
    {
        if (choice == 0)
        {
            animator.runtimeAnimatorController = Resources.Load("Sprites/Idol1Controller") as RuntimeAnimatorController;
            spriteRender.sprite = Resources.Load<Sprite>("Sprites/Idol-Character-1");
        }
        if (choice == 1)
        {
            animator.runtimeAnimatorController = Resources.Load("Sprites/Idol2Controller") as RuntimeAnimatorController;
            spriteRender.sprite = Resources.Load<Sprite>("Sprites/Idol-Character-2");
        }
        if (choice == 2)
        {
            animator.runtimeAnimatorController = Resources.Load("Sprites/Idol3Controller") as RuntimeAnimatorController;
            spriteRender.sprite = Resources.Load<Sprite>("Sprites/Idol-Character-3");
        }
        if (choice == 3)
        {
            animator.runtimeAnimatorController = Resources.Load("Sprites/Idol4Controller") as RuntimeAnimatorController;
            spriteRender.sprite = Resources.Load<Sprite>("Sprites/Idol-Character-4");
        }
    }
    

    private void loseFans()
    {
        if (fanFollowers.Count > 0)
        {
            for(var i=0; i < Mathf.RoundToInt(fanFollowers.Count*0.25f); i++)
            {
                 int choice = Random.Range(0, fanFollowers.Count-1);
                 Transform fan = fanFollowers[choice];
                 fan.GetComponent<FanController>().returnToNormal();
                 fanFollowers.RemoveAt(fanFollowers.Count - 1);
            }
        }
    }

    private void FixedUpdate()
    {
        if (isGrounded)
        {
            if (!isGrab)
            {
                if (Mathf.Abs(Input.GetAxisRaw(horizontalControl)) >= 0.1 || Mathf.Abs(Input.GetAxisRaw(verticalControl)) >= 0.1)
                {
                    faceDir.x = Mathf.Sign(Input.GetAxisRaw(horizontalControl));
                    faceDir.y = Input.GetAxisRaw(verticalControl);
                    speed = walkspeed;

                    changeAnimationState(STATE_WALK);
                }
                else
                {
                    speed = 0f;
                    changeAnimationState(STATE_IDLE);
                }

                if (Input.GetButtonDown(fire1Control) || Input.GetButtonDown(fire2Control))
                {
                    isGrab = true;
                    slidespeed = 35.0f;
                }
            }
            else
            {
                changeAnimationState(STATE_CHARGE);
                slidespeed -= 1f;
                speed = slidespeed;
                if (slidespeed <= 0f)
                {
                    isGrab = false;
                    changeAnimationState(STATE_IDLE);
                }
            }
        }
        if (moveDir.x < 0)
        {
            spriteRender.flipX = false;
        } 
        if(moveDir.x > 0)
        {
            spriteRender.flipX = true;
        }
        if (currentControl == 1)
        {
            globalObject.GetComponent<GlobalScript>().totalP1Followers = fanFollowers.Count;
        }
        if (currentControl == 2)
        {
            globalObject.GetComponent<GlobalScript>().totalP2Followers = fanFollowers.Count;
        }
        rigidBody.MovePosition(rigidBody.position + transform.TransformDirection(moveDir) * speed * Time.deltaTime);
    }

    private void OnCollisionEnter(Collision collision)
    {
        if (collision.gameObject.tag == "Untagged")
            return;
        if (collision.gameObject.tag == "Fan" && isGrab)
        {
            slidespeed = 0;
            speed = 0;
            if (collision.gameObject.GetComponent<FanController>().fanFollowing != this.transform)
            {
                fanFollowers.Add(collision.gameObject.transform);
            }
        }
        if (collision.gameObject.tag == "Fan")
        {
            if (collision.gameObject.GetComponent<FanController>().isCharge)
            {
                loseFans();
                changeAnimationState(STATE_HIT);
                isGrounded = false;
                Vector3 direction = (transform.position - collision.transform.position).normalized;
                GetComponent<Rigidbody>().velocity = new Vector3(direction.x * pushBack, 4f, direction.z * pushBack);
            }
        }
        if (collision.gameObject.tag == "Idol")
        {
            if (collision.gameObject.GetComponent<IdolController>().isGrab)
            {
                if (!isGrab)
                {
                    loseFans();
                    changeAnimationState(STATE_HIT);
                    isGrounded = false;
                    Vector3 direction = (transform.position - collision.transform.position).normalized;
                    GetComponent<Rigidbody>().velocity = new Vector3(direction.x * pushBack, 4f, direction.z * pushBack);
                }
                else
                {
                    Vector3 direction = (transform.position - collision.transform.position).normalized;
                    GetComponent<Rigidbody>().velocity = new Vector3(direction.x * (pushBack * 2), 0f, direction.z * (pushBack * 2));
                }
            }
        }
        if (collision.gameObject.tag == "Ground")
        {
            isGrounded = true;
        }
    }

    void changeAnimationState(int state)
    {

        if (_currentAnimationState == state)
            return;

        switch (state)
        {

            case STATE_WALK:
                animator.SetInteger("state", STATE_WALK);
                break;

            case STATE_CHARGE:
                animator.SetInteger("state", STATE_CHARGE);
                break;

            case STATE_HIT:
                animator.SetInteger("state", STATE_HIT);
                break;

            case STATE_IDLE:
                animator.SetInteger("state", STATE_IDLE);
                break;

        }

        _currentAnimationState = state;
    }
}
