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

public class BishopScript : Piece
{

    const float jumppresscanceltime = 4;

    GameObject crosshair;

    ChessScript cs;

    
    
    float jumplength;
    float jumpstarttime;
    float jumpleft;
    Vector3 jumpprevposition;

    Quaternion origrot;
    Vector3 vec;

    bool jumppressed;
    float jumppressstarttime;

    bool walkdir;
    bool eatdir;

    bool nevermoved;

    Vector3 origchpos;

    float AIrotvel;
    int ddd;
    float AIturnstarted;

    public override void Awake()
    {
       
        base.Awake();
        crosshair = transform.Find("CrossHair").gameObject;
        origchpos = crosshair.transform.localPosition;
        nevermoved = true;
        //weorf = false;
        state = "inactive";
        GetComponent<Rigidbody>().centerOfMass = GetComponent<Rigidbody>().centerOfMass + new Vector3(0, -1f, 0);
        GetComponent<Rigidbody>().mass = 0.6f;
        cs = GameObject.Find("Camera").GetComponent<ChessScript>();
        //timetotakewoirj = Time.time;
    }

    // Update is called once per frame
    void Clicked()
    {
        ddd = 15;
        AIturnstarted = Time.time;
        if (state != "inactive") return;
        if (cs.immediateturn != player) return;
        jumppressed = false;
        cs.Intercepted();
        state = "aim";
        cs.wannarotation = Quaternion.Euler(0, transform.rotation.eulerAngles.y, 0);
        //print("clickedsetwanna");
    }

    public bool GoodDirection()
    {
        float y = transform.rotation.eulerAngles.y;
        float thres = 5f;
        if (y > 45 - thres && y < 45 + thres) return true;
        if (y > 135 - thres && y < 135 + thres) return true;
        if (y > 225 - thres && y < 225 + thres) return true;
        if (y > 315 - thres && y < 315 + thres) return true;
        return false;
    }

    private float JumpLengthFromTime()
    {
        return (Time.time - jumppressstarttime) * 10;
    }

    public override void InformHit(Collider c)
    {
        //print("I hit am " + player.ToString());
        int otherplayer = c.transform.GetComponent<Piece>().player;
        if (otherplayer != player || true) // && (GetComponent<Rigidbody>().velocity.magnitude < collision.rigidbody.velocity.magnitude))
        {
            Vector3 diff = c.transform.position - transform.position;
            float forwo = Vector3.Dot(diff, transform.forward);
            diff = (diff - transform.forward * forwo * 0.4f).normalized;

            diff = new Vector3(diff.x, 0, diff.z);

            c.GetComponent<Rigidbody>().velocity = Vector3.zero;
            c.transform.position = c.transform.position + Vector3.up * 0.2f;

            c.GetComponent<Rigidbody>().AddForce(diff * 400 * 1 + Vector3.up * 300 * 1); //AddExplosionForce(1000, transform.position, 50);

            GetComponent<Rigidbody>().velocity = GetComponent<Rigidbody>().velocity / 3;

            StopJump();
        }
    }

    public void FixedUpdate()
    {
        if (state == "jumping")
        {

            float a = (transform.position - jumpprevposition).magnitude;
            jumpprevposition = transform.position;
            if (a < 2) jumpleft -= a; // teleports...
            //print(jumplength);
            if (jumpleft <= 0) // || Time.time - jumpstarttime > 5)
            {
                StopJump();
            }
            else
            {
                //print("moving" + Time.time.ToString());
                if (GetComponent<Rigidbody>().velocity.magnitude < 3f)
                    GetComponent<Rigidbody>().AddForce(transform.forward * 20 + Vector3.up * 5);
                //print(GetComponent<Rigidbody>().velocity);
            }
        }
    }

    public override void Update()
    {
        base.Update();
        if (cs.state == "checkmate") return;
        if (power > 0)
        {
            power -= 1;
            transform.position = new Vector3(Random.Range(-16, 16), 2, Random.Range(-16, 16));
        }
        if (jumppressed && !amAI)
        {
            Vector3 forward = new Vector3(transform.forward.x, 0, transform.forward.z);
            Vector3 poso = new Vector3(transform.position.x, 0, transform.position.z);
            crosshair.transform.position = poso + forward * JumpLengthFromTime() + new Vector3(0, 0.53f, 0);
        }
        if (state == "aim")
        {
            if (amAI && Time.time - AIturnstarted > 0.6f) ddd = 5;

            if (!amAI)
                instructions.text = "Aim me diagonally with your mouse, and hold space to tell me where I should go. \n A very long press cancels the move. \n For the Queen!";
            else
                instructions.text = "The AI is thinking of moving this \"bishop\".";
            if (GoodDirection())
            {
                cs.CouldMove(true);
            }
            else
            {
                //print("false");
                cs.CouldMove(false);
            }
            cs.wannaposition = transform.position + Vector3.up * 3f - transform.forward * 2.5f;
            if (!amAI)
            {
                //Read mouse input values.
                float x = Input.GetAxis("Mouse X");
                float y = Input.GetAxis("Mouse Y");

                float speed = 3f;
                //Rotate the player right and left
                transform.Rotate(0, x * speed, 0);
            }
            else
            {
                AIrotvel += Random.Range(-0.5f, 0.5f);
                transform.Rotate(0, AIrotvel, 0);
                if (Mathf.Abs(AIrotvel) > 15) AIrotvel = AIrotvel / Mathf.Abs(AIrotvel) * 15;
            }

            //Look up and down only with your camera
            // cs.GetComponent<Camera>().transform.Rotate(Vector3.up, x*speed); // y * speed, x * speed, 0);
            cs.wannarotation = transform.rotation;
            cs.wannarotation = Quaternion.AngleAxis(20, transform.right) * cs.wannarotation;

            //CorrectDirections();

            if (!amAI && Input.GetKey(KeyCode.Escape) || amAI && Random.Range(0, 200) == 0)
            {
                state = "inactive";
                cs.SendMessage("CancelMove");
            }
            if (!amAI && Input.GetKeyDown(KeyCode.Space))
            {
                jumppressed = true;
                jumppressstarttime = Time.time;
                crosshair.GetComponent<SpriteRenderer>().enabled = true;
            }
            if (!amAI && Input.GetKeyUp(KeyCode.Space) || amAI && Random.Range(0, ddd) == 0)
            {

                if ((amAI || Time.time - jumppressstarttime < jumppresscanceltime) && GoodDirection())
                {

                    bool AIcancel = false;
                    if (!amAI)
                    {
                        jumplength = JumpLengthFromTime();
                        jumpleft = JumpLengthFromTime();
                    }
                    else
                    {
                        float len = Random.Range(0, 32);
                        LayerMask mask;
                        mask = 1 << LayerMask.NameToLayer("Default");
                        RaycastHit hitInfo;
                        bool boardhit = Physics.Raycast(transform.position + transform.forward*len + Vector3.down*4,
                            Vector3.up, out hitInfo, 8, mask);
                        if (!boardhit) AIcancel = true;
                        jumplength = len;
                        jumpleft = len;
                    }

                    if (!AIcancel)
                    {

                        GetComponent<Rigidbody>().velocity = Vector3.zero;
                        transform.position = transform.position + Vector3.up * 0.1f;
                        cs.SendMessage("NextTurn");
                        state = "jumping";
                        GetComponent<Collider>().material = Resources.Load<PhysicMaterial>("SlideMaterial");
                        jumpprevposition = transform.position;
                        jumpstarttime = Time.time;

                        crosshair.GetComponent<SpriteRenderer>().enabled = false;
                        crosshair.transform.localPosition = origchpos;
                    }
                    //print("crossheiar on");

                }
                else
                {
                    jumppressed = false;
                    crosshair.GetComponent<SpriteRenderer>().enabled = false;
                }
            }
        }
    }

    void StopJump()
    {
        state = "inactive";
        cs.IHaveStopped(this);
        GetComponent<Collider>().material = Resources.Load<PhysicMaterial>("FrictionMaterial");
    }

}
