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

public class RookScript : Piece
{

    const float jumppresscanceltime = 4;

    GameObject crosshair;

    ChessScript cs;

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

    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.7f;
        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 < thres || y > 360 - thres) return true;
        if (y > 90 - thres && y < 90 + thres) return true;
        if (y > 180 - thres && y < 180 + thres) return true;
        if (y > 270 - thres && y < 270 + 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) // && (GetComponent<Rigidbody>().velocity.magnitude < collision.rigidbody.velocity.magnitude))
        {
            Vector3 diff = c.transform.position - transform.position;
            float forwo = Vector3.Dot(diff, transform.right);
            diff = (diff - transform.right * forwo).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 * 900 * 1 + Vector3.up * 300 * 1); //AddExplosionForce(1000, transform.position, 50);
            c.GetComponent<Rigidbody>().rotation = Quaternion.Euler(Random.Range(-180, 180), Random.Range(-180, 180), Random.Range(-180, 180));
            float t = 30 * (power + 1);
            c.GetComponent<Rigidbody>().angularVelocity = new Vector3(Random.Range(-t, t), Random.Range(-t, t), Random.Range(-t, t));

            GetComponent<Rigidbody>().velocity = GetComponent<Rigidbody>().velocity / (3 - Mathf.Min(power, 2));

            if (power == 0) StopJump();
        }
        else
        {
            //print("shoot self...");
            Vector3 diff = c.transform.position - transform.position;
            float forwo = Vector3.Dot(diff, transform.forward);
            //diff = (diff - transform.forward * forwo).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;

            GetComponent<Rigidbody>().AddForce(-diff * 600 * 1 + Vector3.up * 1200 * 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;
            jumpleft -= a;
            if (jumpleft <= 0) // || Time.time - jumpstarttime > 5)
            {
                StopJump();
            }
            else
            {
                if (GetComponent<Rigidbody>().velocity.magnitude < 2f)
                    GetComponent<Rigidbody>().AddForce(transform.forward * 20 * (power * 2 + 1) + Vector3.up * 5);
            }
        }
    }

    public override void Update()
    {
        base.Update();
        if (cs.state == "checkmate") return;
        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 = 1;

            //string letters = "\u25B2\u0482\u060E\u25B2\u0482\u0FCC\u1254 \u19DF\u19F1\u12E5\u214C\u060E\u06DE\u060F\u2363\u12B9\u237E\u12EC\u23E3 \u06DE \u25B2\u0482\u060E\u06DE\u060F\u2363\u12B9\u237E\u12EC\u23E3\u060F\u2363\u12B9\u237E\u12EC\u23E3";
            string letters = "\u1314\u232D\u2339 \u06E9\u06FD\u07F6\u09FA\u0BF5\u0F15\u0FCC\u1254\u19DF\u19F1\u12E5\u214C\u25B2\u25B2\u25BC\u25BC\u25C0\u25B6\u25C0\u25B6BA \u218A\u1307\u21A2\u21AF\u21ED\u1314\u232D\u2339\u2363\u12B9\u237E\u12EC\u23E3"; // 
            // \u1314\u232D\u2339 \u06E9\u06FD\u07F6\u09FA\u0BF5\u0F15
            // \u19DF\u19F1\u12E5\u0F1C\u0FC7\u0FCC\u1254
            // \u218A\u1307\u21A2\u21AF\u21ED\u1314\u232D\u2339\u2363\u12B9\u237E\u12EC\u23E3
            //string letters = "\u0FCC\u1254\u19DF\u19F1\u12E5\u214C";
            //\u1307
            if (!amAI)
                instructions.text = letters;
            else
                instructions.text = "\u1314\u232D\u2339 \u06E9\u06FD\u07F6\u218A\u1307\u21A2\u21AF\u21ED\u1314\u232D\u2339\u2363\u12B9\u237E\u12EC\u23E3"; // ";

            if (GoodDirection())
            {
                cs.CouldMove(true);
            }
            else
            {
                cs.CouldMove(false);
            }
            cs.wannaposition = transform.position + Vector3.up * 3f - transform.forward * 2.5f;
            //print("aim" + GetComponent<Rigidbody>().velocity.ToString());
            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) > 10) AIrotvel = AIrotvel / Mathf.Abs(AIrotvel) * 10;
            }

            //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;

                        LayerMask ownmask;
                        if (player == 1)
                            ownmask = 1 << LayerMask.NameToLayer("White");
                        else
                            ownmask = 1 << LayerMask.NameToLayer("Black");
                        RaycastHit hitInfo2;
                        bool owncasthit = Physics.SphereCast(transform.position, 1.5f, transform.forward, out hitInfo, 4f, ownmask) ||
                            Physics.Raycast(transform.position, transform.forward, out hitInfo2, 4f, ownmask);
                        if (owncasthit) AIcancel = true;
                    }

                    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;
                    }
                }
            }
        }
    }

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

}
