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

public class BishopController : MonoBehaviour, IPooledObject{

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

    [Space]
    [Range(0, .3f)] [SerializeField] float movementSmoothingTime = .1f;
    [SerializeField] float maxDistance;

    [Space]
    [SerializeField] LayerMask whatIsEnemy;

    Vector3[] possibleRightPositions;
    Vector3[] possibleLeftPositions;
    Vector3[] possibleForwardPositions;
    Vector3[] possibleBackPositions;

    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.DrawLine(transform.position, transform.position + new Vector3(1, 0, 1) * maxDistance);
            Gizmos.DrawLine(transform.position, transform.position + new Vector3(-1, 0, 1) * maxDistance);
            Gizmos.DrawLine(transform.position, transform.position + new Vector3(1, 0, -1) * maxDistance);
            Gizmos.DrawLine(transform.position, transform.position + new Vector3(-1, 0, -1) * maxDistance);

            Gizmos.color = Color.magenta;
            for (float i = 0; i <= maxDistance; i += 1.25f){
                if (i != 0){
                    Gizmos.DrawSphere(transform.position + new Vector3(1, 0, 1) * i, .15f);
                    Gizmos.DrawSphere(transform.position + new Vector3(-1, 0, 1) * i, .15f);
                    Gizmos.DrawSphere(transform.position + new Vector3(1, 0, -1) * i, .15f);
                    Gizmos.DrawSphere(transform.position + new Vector3(-1, 0, -1) * i, .15f);
                }
            }
        }
    }

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

        currentPosition = positionToGo;

        possibleRightPositions = new Vector3[6];
        possibleLeftPositions = new Vector3[6];
        possibleForwardPositions = new Vector3[6];
        possibleBackPositions = new Vector3[6];
        int currentRound = 1;

        for (float i = 0; i <= maxDistance; i += 1.25f){
            if (i != 0){
                possibleRightPositions[currentRound - 1] = currentPosition + new Vector3(1, 0, 1) * i;
                possibleLeftPositions[currentRound - 1] = currentPosition + new Vector3(-1, 0, 1) * i;
                possibleForwardPositions[currentRound - 1] = currentPosition + new Vector3(1, 0, -1) * i;
                possibleBackPositions[currentRound - 1] = currentPosition + new Vector3(-1, 0, -1) * i;
                currentRound++;
            }
        }
        availablePositions = new Vector3[24];
        //Right
        for (int i = 0; i < possibleRightPositions.Length - 1; i++){
            if (Physics.CheckSphere(possibleRightPositions[i], .3f, whatIsEnemy)){
                break;
            }else{
                availablePositions[i] = possibleRightPositions[i];
            }
        }

        //Left
        for (int i = 0; i < possibleLeftPositions.Length - 1; i++){
            if (Physics.CheckSphere(possibleLeftPositions[i], .3f, whatIsEnemy)){
                break;
            }else{
                availablePositions[i + 5] = possibleLeftPositions[i];
            }
        }

        //Forward
        for (int i = 0; i < possibleForwardPositions.Length - 1; i++){
            if (Physics.CheckSphere(possibleForwardPositions[i], .3f, whatIsEnemy)){
                break;
            }else{
                availablePositions[i + 11] = possibleForwardPositions[i];
            }
        }

        //Back
        for (int i = 0; i < possibleBackPositions.Length - 1; i++){
            if (Physics.CheckSphere(possibleBackPositions[i], .3f, whatIsEnemy)){
                break;
            }else{
                availablePositions[i + 17] = possibleBackPositions[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;
            }
        }
    }
}
