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

public class KnightController : MonoBehaviour, IPooledObject{

    [Range(1, 5)] [SerializeField] int framesToMove = 1;
    int currentFrame = 1;
    bool moving;

    [Space]
    [Range(0, .3f)] [SerializeField] float movementSmoothingTime = .1f;
    [SerializeField] Vector3[] possiblePositions;
    [SerializeField] LayerMask whatIsEnemy;

    Vector3[] availablePositions;
    public Vector3 positionToGo;
    Vector3 currentPosition;
    Vector3 velocity;

    Transform player;

    void Awake(){
        player = FindObjectOfType<PlayerController>().transform;
        FindObjectOfType<PlayerController>().onMove.AddListener(() => Move());
    }

    // Start is called before the first frame update
    public void OnObjectSpawn(){
        moving = false;
        positionToGo = currentPosition = transform.position;
        currentFrame = 1;
    }

    // Update is called once per frame
    void Update(){
        if (Vector3.Distance(transform.position, positionToGo) > .1f){
            transform.position = Vector3.SmoothDamp(transform.position, positionToGo, ref velocity, movementSmoothingTime);
        }else if (Vector3.Distance(transform.position, positionToGo) < .1f){
            transform.position = positionToGo;
        }
    }

    void OnDrawGizmos(){
        if (!Application.isPlaying){
            Gizmos.color = Color.red;
            Gizmos.DrawSphere(transform.position + possiblePositions[0], .15f);
            Gizmos.DrawSphere(transform.position + possiblePositions[1], .15f);
            Gizmos.DrawSphere(transform.position + possiblePositions[2], .15f);
            Gizmos.DrawSphere(transform.position + possiblePositions[3], .15f);
            Gizmos.DrawSphere(transform.position + possiblePositions[4], .15f);
            Gizmos.DrawSphere(transform.position + possiblePositions[5], .15f);
            Gizmos.DrawSphere(transform.position + possiblePositions[6], .15f);
            Gizmos.DrawSphere(transform.position + possiblePositions[7], .15f);
        }
    }

    void Move(){
        if (currentFrame < framesToMove){
            currentFrame++;
            moving = false;
            return;
        }
        currentFrame = 1;
        moving = true;
        if (gameObject.activeSelf){
            StartCoroutine(ResetMoving());
        }

        currentPosition = positionToGo;

        availablePositions = new Vector3[8];
        for (int i = 0; i < availablePositions.Length - 1; i++){
            if (!Physics.CheckSphere(currentPosition + possiblePositions[i], .3f, whatIsEnemy)){
                availablePositions[i] = (currentPosition + possiblePositions[i]);
            }
        }

        float nearestDist = float.MaxValue;
        Vector3 nearestPos = new Vector3();
        foreach (Vector3 v in availablePositions){
            if (v != Vector3.zero){
                float dist = Vector3.Distance(v, player.position);
                if (dist < nearestDist){
                    nearestDist = dist;
                    nearestPos = v;
                }
            }
        }

        positionToGo = (nearestPos == Vector3.zero) ? currentPosition : nearestPos;
    }

    IEnumerator ResetMoving(){
        yield return new WaitForSeconds(movementSmoothingTime * 3);
        moving = false;
    }

    void OnTriggerEnter(Collider col){
        if (col.CompareTag("Limits")){
            positionToGo = currentPosition;
        }
    }

    void OnCollisionEnter(Collision col){
        if (col.gameObject.layer == Mathf.RoundToInt(Mathf.Log(whatIsEnemy.value, 2))){
            BishopController bishop = col.gameObject.GetComponent<BishopController>();
            KnightController knight = col.gameObject.GetComponent<KnightController>();
            PawnController pawn = col.gameObject.GetComponent<PawnController>();
            RookController rook = col.gameObject.GetComponent<RookController>();
            if (bishop != null){
                if (bishop.positionToGo == positionToGo){
                    if (Vector3.Distance(transform.position, positionToGo) > Vector3.Distance(col.transform.position, bishop.positionToGo)){
                        positionToGo = currentPosition;
                    }
                }
            }else if (knight != null){
                if (knight.positionToGo == positionToGo){
                    if (Vector3.Distance(transform.position, positionToGo) > Vector3.Distance(col.transform.position, knight.positionToGo)){
                        positionToGo = currentPosition;
                    }
                }
            }else if (pawn != null){
                if (pawn.positionToGo == positionToGo){
                    if (Vector3.Distance(transform.position, positionToGo) > Vector3.Distance(col.transform.position, pawn.positionToGo)){
                        positionToGo = currentPosition;
                    }
                }
            }else if (rook != null){
                if (rook.positionToGo == positionToGo){
                    if (Vector3.Distance(transform.position, positionToGo) > Vector3.Distance(col.transform.position, rook.positionToGo)){
                        positionToGo = currentPosition;
                    }
                }
            }
        }

        if (col.gameObject.tag == "Player"){
            PlayerController player = col.gameObject.GetComponent<PlayerController>();
            if (player.positionToGo == positionToGo && moving){
                player.Damage();
                positionToGo = currentPosition;
            }
        }
    }
}
